JavaScript function that returns AJAX call data

This question already has an answer here:

  • How do I return the response from an asynchronous call? 33 answers

  • With jQuery 1.5, you can use the brand-new $.Deferred feature, which is meant for exactly this.

    // Assign handlers immediately after making the request,
    // and remember the jqxhr object for this request
    var jqxhr = $.ajax({ url: "example.php" })
        .success(function() { alert("success"); })
        .error(function() { alert("error"); })
        .complete(function() { alert("complete"); });
    
    // perform other work here ...
    
    // Set another completion function for the request above
    jqxhr.complete(function(){ alert("second complete"); });
    

    Source


    You can't return data returned by an AJAX call unless you want to call it synchronously (and you don't – trust me). But what you can return is a promise of a data returned by an AJAX call and you can do it actually in a very elegant way.

    ( UPDATE: Please note that currently jQuery Promises are not compatible with the Promises/A+ specification - more info in this answer.)

    Basically you can return the return value of your $.ajax(...) call:

    function checkUserIdExists(userid){
        return $.ajax({
            url: 'theurl',
            type: 'GET',
            cache: false,
            data: {
               userid: userid
            }
        });
    }
    

    and someone who calls your function can use it like this:

    checkUserIdExists(userid).success(function (data) {
        // do something with data
    });
    

    See this post of mine for a better explanation and demos if you are interested.


    你可以传递一个回调函数:

    function checkUserIdExists(userid, callback) {
        $.ajax({
            ...
            success: callback
        });
    }
    
    checkUserIdExists(4, function(data) {
    
    });
    
    链接地址: http://www.djcxy.com/p/9484.html

    上一篇: JavaScript异步返回值/赋值jQuery

    下一篇: 返回AJAX调用数据的JavaScript函数