保存来自jQuery ajax函数的响应 [英] Save response from jQuery ajax function

查看:69
本文介绍了保存来自jQuery ajax函数的响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义函数,该函数调用ajax请求,并且能够将响应数据保存到变量中并返回它.始终返回 0 ,但显示警告,例如3712.

I've got a custom function, which calls ajax request and I'm able to save response data to variable and return it. 0 is always returned, but alert shows e.g. 3712.

这是函数:

function getNo(index, val) {

var $ret = 0;

$('body').showLoading();
$.ajax({
    type: 'POST',
    url: BASE_URL + 'tools/no.php?id='+index+'&value='+val,
    data: $("#form").serialize(),
    cache: false,
    success: function(data) {
        $('body').hideLoading();
        alert('data: ' + data);
        $ret = data;
    }
});
return $ret;
}

推荐答案

由于异步调用,此操作将返回 0 .相反,我建议您传递一个回调方法来处理响应.

This will return ZERO because of the asynchronous call. Rather I would suggest you to pass a callback method to work with the response.

请参见以下示例:

function getNo(index, val, callback) {
    var $ret = 0;

    $('body').showLoading();
    $.ajax({
        type: 'POST',
        url: BASE_URL + 'tools/no.php?id=' + index + '&value=' + val,
        data: $("#form").serialize(),
        cache: false,
        success: function (data) {
            $('body').hideLoading();
            callback(data);
        }
    });
    return $ret;
}

//USAGE
getNo(3, "value", function (data) {
    //do something with data responded from the server
    alert(data);
});

这篇关于保存来自jQuery ajax函数的响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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