在它之外使用ajax respone是否可行?

data_response$.post()之外使用data_response方法?

这是我使用的代码的一部分:

 $.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

是否没有办法在全球范围内获得该响应?

没有; $.post异步执行,因此当您调用console.log ,AJAX请求仍在运行,尚未产生响应。 这是回调函数的目的:提供在请求完成运行的代码。 如果将console.log移动到回调函数中,它应该工作:

 $.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"); 

更新:如果您希望响应数据全局可用,您可以在全局范围内声明变量,如下所示:

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

当然,您可以确定response实际上已填充了值的唯一上下文是在行response = data_response;之后提供给$.post的回调函数中response = data_response; 。 如果你想在脚本的任何其他阶段使用它,那么你必须先检查它的值; 像这样的东西:

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

请注意,如果您在$.post调用之后直接放置此代码,它将不会执行任何操作; 它只会在POST请求完成后执行,在其他一些异步回调(可能是某种类型的UI交互事件)中执行。

只需在回调之外声明变量,使其范围限定为您可以从以下位置访问的代码的一部分:

 var response; $.post('do.php', { OP: "news_search", category: cat_id }, function(data_response){ response = data_response; } }, "json"); console.log(response); //response is now defined - It won't be populated yet though. 

正如上面的代码中所指出的,虽然将定义响应,但是在调用console.log时不会填充它,但是如果在回调触发后的某个时刻访问变量,它将被填充。

如果你沿着这条路走下去,你可能想要使用模块模式或闭包来避免将响应变量放在全局范围内(你可能想要公平地做到这一点)

Crockford的模块模式: http : //www.yuiblog.com/blog/2007/06/12/module-pattern/

您可以使用aa变量,并在脚本中的任何位置检查done(),如果已完成,它将立即执行,否则它将在ajax调用完成后执行。

 var XHR = $.post('do.php', { OP: "news_search", category: cat_id }, function(data_response){ // do somehing with data_response } }, "json"); function doSomethingElse() { XHR.done(function(response) { console.log(response); }); } 

如果您需要在$ .post()之外使用响应,并且您需要确保在$ .post()调用之后立即填充此值,您可以尝试以同步方式进行“POST”调用。 这不能用$ .post()进行,但可以使用$ .ajax()来制作:

 var returnedData = null; $.ajax({ type: 'POST', url: 'do.php', data: { OP: "news_search", category: cat_id }, success: function (response) { returnedData = response; }, dataType: "text" }); console.log(returnedData ); 

我得到它像这样工作:

 var returnedData = {}; //Declaring Object var not just var $.ajax({ type: 'POST', url: 'do.php', data: { OP: "news_search", category: cat_id }, success: function (response) { returnedData.result1=response; //Add response into the Object created outside the ajax }, dataType: "json" }); console.log(returnedData);//inside it you can get returnedData.result1