开发者

extract the ajax response in jQuery?

开发者 https://www.devze.com 2023-02-14 05:54 出处:网络
How can i extract the returned response of the ajax response? to catch the response i should write: $.post(\'server.php\',{x : 9}, function(response){

How can i extract the returned response of the ajax response? to catch the response i should write:

$.post('server.php',{x : 9}, function(response){
    alert(response);
});

Now, how can i take the " response " out of the function(){} ?, because it doesn't exist outside .. and i wanna compare it with some other value, i attempted to assign it to a global var and to a jQuery object " $response ", but it always "undefined" while the " response " it self have the correct value !.. Generally i want it this way, if possible :)

response= $.post('.开发者_如何转开发.',{.. : ..});

Thanks in advance :)


You can't. Just as you can't do:

var foo = jQuery('button').click(somefunction);

… and expect to get the return value in foo.

Ajax just sets up some code to run when the HTTP response arrives from the server.

You need to design your code so that the callback function can do what you want to do with the data.


What are wanting to do ain't going to happen since the ajax call is not synchronous. Solution, put whatever logic you need with the response in the callback function and use closure variables for context.


You have to do the comparison in the callback method. Using the new and shiny Deffered object introduced in jQuery 1.5 you can do this in a nice readable manner:

$.when(postToServer())
    .then(function(response){
        // Logic to compare response
    });

function postToServer(){
    var dfd = $.Deferred();
    $.post('server.php', {x : 9}, dfd.resolve);
    return dfd.promise();
};


Usually it goes this way, if your dataType = "json":

function myFunc ()
{
    var jqHXR = jQuery.ajax({
        async : false,
        dataType : "json"
    });

    return jQuery.parseJSON(jqXHR.responseText);
}

Returns the parsed value as a valid Jscript object. Make sure its Synchronous XHR call though, by providing { 'async' : false } parameter to jQuery.ajax(); as shown above.

0

精彩评论

暂无评论...
验证码 换一张
取 消