【发布时间】:2011-03-17 22:41:36
【问题描述】:
我是 AJAX 的新手。任务是我必须从 php 文件中获取数据并将其存储在 javascript 变量中。我经历了很多例子,但没有发现有帮助。 我在这里给出一个伪html代码:
<html>
<head>
<script>
function ajaxfunction()
{
//code for httprequest
**call the php file declare a variable and store the response of php**
//return the variable
}
</script>
</head>
<body>
//my code for displaying a map
**mainvariable=ajaxfunction();//storing the value of subvariable(data from php) in mainvariable**
//use the mainvariable and do the remaining task
<body>
我的php代码:
<?php
$file=fopen("datapoints.txt","r");
$read=fread($file,filesize("datapoints.txt"));
fclose($file);
echo $read;
?>
这里的问题是我的 html 文件中没有任何表单变量可以在调用 php 文件时使用。只是在页面加载时,应该调用“ajaxfunction()”并从 php 获取数据并存储在变量中......
我想你能理解我的问题
非常感谢任何帮助
【问题讨论】:
-
@jakenoble 答案是正确的。
.load()或.get()用于显示内容,而.getJSON()用于获取数据并存储为 jquery 变量。 en.wikipedia.org/wiki/JSON -
基于您的问题,为什么需要 Ajax?您可以在 html 文件中添加 php 标记或简单地将文件重命名为 .php。所以只需简单地以
<input type="text" value="<?php echo $yourPhpVar ?>" />的形式填充 php 变量
标签: php javascript html ajax