难道是更多钞票使用Ajax

难道是更多钞票使用Ajax

本文介绍了难道是更多钞票使用Ajax respone之外呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

采用任何方式 data_response 之外 $。员额()

这是的code我用一部分:

This is part of the code I use:

$.post('do.php', { OP: "news_search", category: cat_id },
    function(data_response){
        var response = data_response; //I need to access this variable outside of $.post()
    }
}, "json");

console.log(response); //response is not defined, is what I get for now

更新

请问有没有办法让这种反应可在全球范围的?

UPDATE

Is there no way of getting that response available globally?

推荐答案

没有; $。交异步执行,所以当你调用的console.log ,AJAX请求仍在运行,并且有不还产生了一个响应。这是回调函数的宗旨:为code要运行的的请求已完成。如果移动的console.log 进入回调函数,它应该工作:

No; $.post executes asynchronously, so when you call console.log, the AJAX request is still running and hasn't yet yielded a response. This is the purpose of the callback function: to provide code to be run after the request has completed. If you move console.log into the callback function, it should work:

$.post('do.php', { OP: "news_search", category: cat_id },
    function(data_response){
        var response = data_response; //I need to access this variable outside of $.post()
        console.log(response);
    }
}, "json");


更新:如果您想响应数据是全局可用,您可以像这样在全球范围内声明的变量:


Update: If you want the response data to be globally available, you can declare the variable in the global scope like so:

var response = null;
$.post('do.php', { OP: "news_search", category: cat_id },
    function(data_response){
        response = data_response;
        console.log(response);
    }
}, "json");

当然,在其中可以肯定的是响应拥有国内唯一的上下文实际上已被填充了一个值是在供给到回调函数 $交行之后响应= data_response; 。如果你想使用它在脚本中任何其他阶段,那么你就必须先检查它的价值;是这样的:

Of course, the only context in which you can be sure that response hasactually been populated with a value is in the callback function supplied to$.post after the line response = data_response;. If you want to use it atany other stage in the script then you'll have to check its value first;something like this:

if (response !== null)
{
    console.log(response);
}

要知道,如果你把它直接在此之后code不会做任何事情。在 $交通话;如果它执行时,就只能用后POST请求完成后,在其他一些异步回调(可能是一个用户界面交互某种情况下)。

Just be aware that this code won't do anything if you put it straight afterthe $.post call; it'll only be useful if it's executed after the POST request has finished, in some other asynchronous callback (perhaps a UI interaction event of some kind).

这篇关于难道是更多钞票使用Ajax respone之外呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 13:31