AJAX-获得从PHP数据 [英] AJAX-Get data from php

查看:112
本文介绍了AJAX-获得从PHP数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个新手,AJAX.The任务是我从一个PHP文件中获取数据,并将其存储在一个javascript变量。我已经经历了很多例子了,但没有找到有用的。 我给一个伪HTML code在这里:

I am a newbie to AJAX.The task is I have to get the data from a php file and store it in a javascript variable. I have gone through many examples but didn't find helpful. I am giving a pseudo html code here:

<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 code:

My php code:

<?php 
  $file=fopen("datapoints.txt","r");
  $read=fread($file,filesize("datapoints.txt"));
  fclose($file); 
  echo $read;
?>

这里的问题是我没有在我的html文件,同时调用PHP文件中使用任何形式的变量。简单地加载网页时,ajaxfunction()应该叫并获得一个变量从PHP和存储数据...............

the problem here is I dont have any form variables in my html file to use while calling php file. simply when the page loads, "ajaxfunction()" should be called and get data from php and store in a variable................

我想你能明白我的问题

任何帮助是极大AP preciated

Any help is greatly appreciated

推荐答案

您可以把jQuery来很好地利用这里。该文档是在这里 http://api.jquery.com/jQuery.ajax/

You can put jQuery to good use here. The docs are here 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文件可以只包含:

Your ajax.php file can just contain:

<?php
    echo json_encode(array("value" => "Hello World"));
?>

这篇关于AJAX-获得从PHP数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆