jquery返回$ .post()函数中的值 [英] Jquery return value from $.post() in function

查看:102
本文介绍了jquery返回$ .post()函数中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为的getCartProducts() Javascript函数,它通过AJAX使用 $。post()它返回一个值。我想让我的函数返回这个值,但我不知道如何去做。



这是我的函数:

 函数getCartProduct(id){
$ .post('core / ajax / getCartProduct.ajax.php',{id:parseInt(id)},function (data){
var result = data;
});
返回结果;
}

我知道这是行不通的,因为te变量结果只在 $。post()函数,但我不知道如何弄明白。

解决方案

添加一个回调函数(AJAX是异步的,所以你的回报在有任何数据返回之前被击中):

  function returnData(param){
console.log(param);

$ / code>

现在将该回调函数作为参数添加到您的AJAX函数中,并让它运行它:

 函数getCartProduct(id,callback){
$ .post('core / ajax / getCartProduct.ajax .php',{id:parseInt(id)},function(data){
callback(data);
});
}

getCartProduct(id,returnData);


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.

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.

解决方案

Add a callback function (AJAX is Asynchronous, so your return is being hit before there is any data to return):

function returnData(param) {
    console.log(param);
}

Now add that callback function as a parameter to your AJAX function, and lets run it:

function getCartProduct(id, callback){
    $.post('core/ajax/getCartProduct.ajax.php', {id: parseInt(id)}, function(data){
        callback(data);
    });
}

getCartProduct(id, returnData);

这篇关于jquery返回$ .post()函数中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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