【问题标题】:AJAX-Get data from phpAJAX-从php获取数据
【发布时间】: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。所以只需简单地以&lt;input type="text" value="&lt;?php echo $yourPhpVar ?&gt;" /&gt; 的形式填充 php 变量

标签: php javascript html ajax


【解决方案1】:

您可以在这里充分利用 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"));
?>

【讨论】:

    【解决方案2】:

    如果你想将数据从 php 发送到 javascript 下来,你可以使用 json_encode。 要使用 php 接收数据,您可以使用 $_GET 和 $_POST(只要您正在编写一个简单的应用程序):)

    对于您的 Ajax 请求,您(我只允许这个问题的作者这样做)可以使用我的 javascript 代码:

    function getRequestObject(){
        var o = null;
        if(window.XMLHttpRequest){
            o = new XMLHttpRequest();
        }else if(window.ActiveXObject){
            try{
                o = new ActiveXObject('Msxml2.XMLHTTP');
            }catch(e1){
                try{
                    o = new ActiveXObject('Microsoft.XMLHTTP');
                }catch(e2){
    
                }
            }
        }
        return o;
    }
    function request(method, adress,sendData,callback){
        var o = getRequestObject();
        var async = (callback!==null);
        if(method === 'GET'){
            if(sendData!=null){adress+="?"+sendData;}
            o.open(method, adress, async);
            o.send(null);
        }else if(method === 'POST'){
            o.open(method, adress, async);
            o.setRequestHeader('Content-Type' , 'application/x-www-form-urlencoded');
            o.send(sendData);
        }
        if(async){
            o.onreadystatechange = function (){
                if(o.readyState==4&&o.status==200){
                    callback(o.responseText);
                }else if(o.readyState==4&&o.status!=200){
                    //Error
                }
            };
        }
        if(async){return ;}
        else{return o.responseText;}
    }
    

    RequestCache 被实现为对象(看看这是如何在 Javascript 中完成的) 但也许 JQuery 左右也可以解决您的任务。

    function RequestCache (){}
    RequestCache.cache = Array();
    RequestCache.getRequest=function (method, adress,sendData,callback,enforceReload){
        if(enforceReload===null){enforceReload=false;}
        var url = method+adress+sendData;
        var newUrl = true;
        if(typeof(enforceReload)==="undefined"||enforceReload===false){
            for(var key in RequestCache.cache){
                if(key===url){
                    newUrl=false;
                    break;
                }
            }
        }
        if(newUrl){
            if(callback){
                request(method, adress,sendData,
                    function(res){
                        RequestCache.cache[url]=res;
                        callback(res);
                    }
                );
            }else{
                RequestCache.cache[url]=request(method, adress,sendData,null);
                return RequestCache.cache[url];
            }
        }else{
            if(callback){
                callback(RequestCache.cache[url]);
            }else{
                return RequestCache.cache[url];
            }
        }
    };
    RequestCache.setRequest = function (method, adress,sendData,result){
        var url = method+adress+sendData;
        RequestCache.cache[url] = result;
    };
    

    【讨论】:

      【解决方案3】:

      据我所知,最简单的方法是使用 jQuery .load() 函数或 .get() 函数将其存储在变量中。

      【讨论】:

        猜你喜欢
        • 2023-03-17
        • 2013-05-17
        • 2018-05-19
        • 1970-01-01
        • 2019-11-26
        • 2013-04-10
        • 2015-07-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多