Jquery 函数中 $.post() 的返回值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17394362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Jquery return value from $.post() in function
提问by Daniel Gelling
I've got a Javascript function called getCartProducts()
which gets a JSON array via AJAX using $.post()
which returns a value. I want to let my function return that value, but I don't know how to do that.
我有一个 Javascript 函数调用getCartProducts()
它通过 AJAX 获取一个 JSON 数组,使用$.post()
它返回一个值。我想让我的函数返回那个值,但我不知道该怎么做。
Here's my function:
这是我的功能:
function getCartProduct(id){
$.post('core/ajax/getCartProduct.ajax.php', {id: parseInt(id)}, function(data){
var result = data;
});
return result;
}
I know that this wont work, because te variable result is only active in the $.post()
function, but I don't know how to get it straight.
我知道这行不通,因为 te 变量 result 仅在$.post()
函数中处于活动状态,但我不知道如何弄明白。
回答by tymeJV
Add a callback function (AJAX is Asynchronous, so your return is being hit before there is any data to return):
添加回调函数(AJAX 是异步的,因此在有任何数据要返回之前,您的返回已被命中):
function returnData(param) {
console.log(param);
}
Now add that callback function as a parameter to your AJAX function, and lets run it:
现在将该回调函数作为参数添加到您的 AJAX 函数中,然后运行它:
function getCartProduct(id, callback){
$.post('core/ajax/getCartProduct.ajax.php', {id: parseInt(id)}, function(data){
callback(data);
});
}
getCartProduct(id, returnData);