我是 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"));
?>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)