Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
615 views
in Technique[技术] by (71.8m points)

javascript - jquery ajax returns success when directly executed, but returns error when attached to button, even though server response is 200 OK

This is somewhat related to other similar questions:

jquery ajax returns error but is success

jquery .ajax always returns error - data being added to database

Jquery Ajax Call always returns error

However, my problem doesn't seem to be the data:"json" issue.

My code is a simple POST request to a server and, for testing purposes, it is always returning 200 OK.

If I run the jquery code directly after document ready, it works just fine and calls the success function.

But if I attach it to a on("click") button event, it always return the error function. Nothing has changed on the server and I can see on the console that the right resource is being called.

My main code is located on a js file:

var myObj = function(){
    var url = "myURL";
    this.functionINeed = function(data, cb) {
        ajaxPost(url, data, cb);
    };

    function ajaxPost(url, data, cb){
        $.ajax({
            "url" : url,
            "contentType" : "application/json; charset=UTF-8",
            "data" : data,
            "type" : "POST",
            "success" : function(serverData, textStatus, jqXHR){
                cb(null, {
                    "serverData" : serverData,
                    "textStatus" : textStatus,
                    "jqXHR" : jqXHR
                });
            },
            "error": function (jqXHR, textStatus, errorThrown) {
                cb({
                    "jqXHR" : jqXHR,
                    "textStatus" : textStatus,
                    "errorThrown" : errorThrown
                });
            }
        });
    };
}
//I initialize the object directly on the js file
MyObj = new myObj();

Then, the first scenario: call the function directly on page load:

var data = {
        "action" : "someaction",
        "code" : "somecode"
    }
    MyObj.functionINeed(JSON.stringify(data), function(err, response){
        if(err){
            alert(err.errorThrown);
            return err;
        }else{
            alert(response.textStatus);
            return response;
        }
    });

This works fine: the server is called, the content is returned and JQuery calls the success function.

However, if I attach this code to a button event, it always returns the error function. I am monitoring the server and I am sure it is returning the correct data.

$("#myButton").on("click", function(){
    var data = {
        "action" : "someaction",
        "code" : "somecode"
    }
    MyObj.functionINeed(JSON.stringify(data), function(err, response){
        if(err){
            alert(err.errorThrown);
            return err;
        }else{
            alert(response.textStatus);
            return response;
        }
    });
});

For the records, my server is Node.js with Sails.js, but this doesn't seem to matter.

The many similar questions are somehow related to the data:"json" issue, but I've removed it and the most weird is that the behavior only happens when you attach the code to an event.

I would suspect there is some kind of scoping issue involved (object being instantiated on the file, for ex.), but the server is being correctly called every time. I just can't understand why JQuery interprets all responses as errors (and empty server data).

What am I doing wrong here?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After an insane afternoon trying all kinds of combinations, a light bulb went off and I figured out the problem is that my button html was inside a form.

<form>
    <button></button>
</form>

After changing to a regular div, it worked.

<div>
    <button></button>
</div>

Which is -- to me -- absolutely insane. It seems JQuery captures more information than meets the eye when sending the ajax query, and this was messing the response parsing by expecting some form encoded behavior. Does it mean I cannot have special purpose buttons inside my forms? Since I am using Bootstrap, that's "OK" because I can use the a tags for this (tested and worked). But this seems a JQuery bug (version: 1.11.2)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...