将ajax响应数组存储到变量中以备后用 [英] Storing ajax response array into a variable for later usage

查看:62
本文介绍了将ajax响应数组存储到变量中以备后用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将AJAX响应存储到两个变量x和y或数组中. 我的AJAX响应是一个数组.我能够看到数据,但只能通过它并发出警报. 我需要ajax调用之外的数据

Hi I need to store an AJAX Response into two variables x and y or into a array. My AJAX response is a array. I am able to see the data but only with and alert into che call. I need the data outside the ajax call

var x;
var y;

$.ajax({
    url: 'ajaxload.php',
    dataType: "json",
    success: function (data) {
        x = data.posX;
        y = data.posX;
        alert(x + " " + y);  // I can se data but I need outside ajax call
    }
});

推荐答案

如果我理解正确,则希望稍后在代码中重用ajax响应. 在这种情况下,您的当前代码将无法工作,因为默认情况下,JavaScript引擎不会等待ajax请求的响应.换句话说,以下代码将不起作用:

If I understand correctly, you want to reuse the ajax response later within your code. If that's the case, your current code wouldn't work because by default, the javascript engine doesn't wait for the response of ajax requests. In other words the code below won't work:

<script type="text/javascript">
$(document).ready(function(){
    var x; 
    var y;
    $.ajax({
        url: 'ajaxload.php',
        dataType: "json", 
        success: function(data) { 
            x= data.posX;
            y= data.posX;
            alert (x+" "+y);  // I can se data but I need outside ajax call
        }
    });
    alert(x+" "+y); // You won't see anything, because this data isn't yet populated. The reason for this is, the "success" function is called when the ajax request has finished (it has received a response).
})
</script>

您需要等待ajax响应.为此,您需要对jQuery进行一些修改:

You need to wait for the ajax response. To do that with jQuery you need to slightly modify your code:

<script type="text/javascript">
$(document).ready(function(){
    var data = $.parseJSON($.ajax({
        url:  'ajaxload.php',
        dataType: "json", 
        async: false
    }).responseText); // This will wait until you get a response from the ajax request.

    // Now you can use data.posX, data.posY later in your code and it will work.
    var x = data.posX;
    var y = data.posY;
    alert(x+" "+y);
    alert(data.posX+" "+data.posY);
});
</script>

这篇关于将ajax响应数组存储到变量中以备后用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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