调用Ajax并返回响应 [英] Calling Ajax and returning response

查看:102
本文介绍了调用Ajax并返回响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索了很多问题,但没有得到正确的答案.根据我的研究,我已经实现了以下功能,我了解到ajax调用是异步的,因此它完成了将值传递给全局变量并将其返回的操作,但是我得到了一个空白或未定义的值.我可以使用$('#someid' ).html作为响应或其他一些方法,但我不想实现它们.知道我在这里做错了吗

I have search for so many questions but didnt get the right answer. I have made the following function from what my research i understand that ajax call is async so on its done passing a value to global variable and returning that but i get a blank or undefined value.i can do it with $('#someid').html in response or some other methods but i dont want to implement them . Any idea what i am doing wrong here

function SimpleAjax(form, postData, url)
{
    var returnData;
    var sendData;

    if (form == "") {
        sendData = postData;
    }
    else if (postData == "") {
        sendData = $(form).serialize();

    }

    $.ajax({
        type: 'POST',
        url: url,
        cache: false,
        data: sendData,
        success: function(data)
        {
            if (data != null || typeof data != 'undefined') {
                returnData = data;
            }
        }
    }).done(function(data) {
        returnData = data;
    });

    return returnData;
}​

推荐答案

问题是return returnData;发生在成功执行或完成的功能执行之前.如您所说,它是异步的.但是,您的功能SimpleAjax正在同步运行.

The issue is that the return returnData; happens before your success or done functions execute. As you said, it's asynchronous. However, your function SimpleAjax is running synchronously.

因此它开始Ajax调用$.ajax({ ... });,然后执行return returnData;.

So it starts the Ajax call $.ajax({ ... });, then it executes the return returnData;.

我要做的是不使用全局变量,那只会引起您的头痛.但是,传递一个函数以在成功执行时执行,而不是尝试返回结果.

What I do, is not use a global, that will just cause you headaches. But pass in a function to execute on success, rather than trying to return the result.

类似...

function SimpleAjax(form, postData, url, successCallback)
{
    var returnData;
    var sendData;

    if (form == "") {
        sendData = postData;
    }
    else if (postData == "") {
        sendData = $(form).serialize();

    }

    $.ajax({
        type: 'POST',
        url: url,
        cache: false,
        data: sendData,
        success: successCallback
    });
}​

//TODO: set your input parameters
SimpleAjax(form, postdata, url, function(data) {
    alert(data);
});

这篇关于调用Ajax并返回响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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