我是 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 获取数据并将其存储在变量中......................
我想你能理解我的问题
非常感谢任何帮助
最佳答案
您可以在这里充分利用 jQuery。文档在这里 http://api.jquery.com/jQuery.ajax/ .
例子如下:
<html>
<head>
<!-- Include jquery from Google here -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript">
// Wait till dom is loaded
$(document).ready(function() {
// When id with Action is clicked
$("#Action").click(function()
{
// Load ajax.php as JSON and assign to the data variable
$.getJSON('ajax.php', function(data) {
// set the html content of the id myThing to the value contained in data
$("#myThing").html(data.value);
});
});
});
</script>
</head>
<body>
<a id="Action">Click Me</a>
<p id="myThing"></p>
</body>
</html>
您的 ajax.php 文件可以只包含:
<?php
echo json_encode(array("value" => "Hello World"));
?>
关于php - AJAX-从php获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5346171/