简体   繁体   English

AJAX:将PHP数据存储在Javascript变量中

[英]AJAX: Store PHP data in a Javascript variable

As stated in the title, I have an ajax call. 如标题中所述,我有一个ajax调用。 On the success function I want to store the returned data into a variable for use in my javascript. 关于成功函数,我想将返回的数据存储到一个变量中,以便在我的JavaScript中使用。 randNum.php simply returns a random number every 2 seconds, and I would like to use that number for other functions in my scripts. randNum.php仅每2秒返回一个随机数,我想将该数字用于脚本中的其他函数。 How can I use the data sent back from the php file in my javascript? 如何使用从javascript中的php文件发回的数据? I know there are more logical ways to go about this, but want to know how to accomplish the task this way. 我知道有更多合理的方法可以解决此问题,但是想知道如何以这种方式完成任务。

    var result;
    var interval = 2000;
    function myCall() {
        var request = $.ajax({
            url: "randNum.php",
            type: "GET",            
            dataType: "html",
            success:function (msg) {
                result = msg;  //Not working as I intend
                setTimeout(myCall, interval);
            }
        });
    }

function(){
    do something with result;
}

Declare a Global variable outside of the function and assign response variable to it after the ajax response. 在函数外部声明一个全局变量,并在ajax响应后为其分配响应变量。

var results;
function TestJSONP(){
    $.ajax({
        url: "randNum.php",
        jsonp: "callback",
        dataType: "jsonp",

        success: function (response) {
            console.log(response);
            results = response;
        }
    });
}

You might not need to specify dataType , but use jqXHR.responseText to get the raw response. 您可能不需要指定dataType ,但可以使用jqXHR.responseText来获取原始响应。 Something like 就像是

function myCall() {
    var request = $.ajax({
        url: "randNum.php",
        type: "GET",            
        success:function (data, textStatus, jqXHR) {
            result = jqXHR.responseText;  
            setTimeout(myCall, interval);
        }
    });
}

When you set dataType , and the response is not that type, then the ajax did not succeed and error call back will be invoked. 当您设置dataType ,并且响应不是该类型时,那么ajax不会成功,并且将调用error回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM