2

有什么办法使用data_response外部的$.post()

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

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

更新

有没有办法在全球范围内获得这种响应?

4

5 回答 5

2

不; $.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实际填充了值的上下文是在 $.postline 之后提供的回调函数response = data_response;。如果您想在脚本的任何其他阶段使用它,那么您必须先检查它的值;像这样的东西:

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

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

于 2012-05-18T13:03:59.037 回答
1

只需在回调之外声明变量,以便将其范围限定为您可以从中访问它的代码的一部分:

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/

于 2012-05-18T13:04:20.167 回答
1

您可以使用 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);
    });
}
于 2012-05-18T13:09:28.253 回答
0

如果您需要在 $.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 );
于 2012-05-18T13:14:27.970 回答
0

我让它像这样工作:

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
于 2016-11-29T04:54:07.700 回答