开发者

Why i can't return a Json Object?

I'm getting undefined when i try to return the oject from the function. And i'm pretty sure that the object is not empty otherwise alert(response.html); shouldn't be working.

var Core = {
    "Ajax" : function(url, data){
        $.ajax({
            type: "POST",
            url: host + url,
            data: data,
            success: function(json){
                var respo开发者_JS百科nse = $.parseJSON(json);
                if(response.status == "200"){
                    alert(response.html);
                    return response;
                }
                else{
                    alert(response.html);
                    return false;
                }
            },
            error:function (xhr, ajaxOptions, thrownError){
                alert(xhr.status);
            }
        });
    }
};


You are probably misunderstanding the concept of Ajax, which is asynchronous.

The success callback will be called by the browser when the request has completed. Anything you return in the success callback, will simply vanish.

It is not possible to return something to the line of code that is initiating the request - when the success callback fires, you are already past that line.


You cannot return things from asynchronous functions. The function which calls $.ajax() returns right after calling it - (almost) always before the response has been received. Do whatever you need to do with the response in the success callback.

PS: Add dataType: 'json' to your ajax arguments and use json.status - no need to do the parsing on your own.

Besides that, use Firebug's console to check what you actually get back from the server (alert() is not a debugger)


You cannot return anything from an $.ajax call, it's asynchronous. You need to have it call another callback function and pass it response.

Also, you don't need $.parseJSON(json). Just set dataType: 'json' and jQuery'll parse the JSON for you.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜