php - AJAX-从php获取数据

标签 php javascript html ajax

我是 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/

相关文章:

PHP 警告 : Unknown: Error occured while closing statement in Unknown on line 0

php - 在另一个 php 文件 wordpress 插件中包含一个 php 文件

javascript - PhantomJS:无法在描述中进行设置/拆卸

html - CSS 露台布局

jquery - 在 css 中添加 href 链接到 <a> 标签

php 对象关联数组

php - 获取免费IP地址的算法

javascript - 选择行时(悬停)CSS更改整个行单元格背景

javascript - 经常更新 div 的内容

javascript - 突出显示所选 li 元素的问题