Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

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

jquery - Why does $.ajax call for json data trigger the error callback when http status code is "200 OK"?

I have the following ajax request:

        jQuery.ajax({
            async: true,
            type: "GET",
            url: url,
            data: data,
            dataType: "json",
            success: function(results){
                currentData = results;
            },
            error: function(xhr, ajaxOptions, thrownError){
                if (xhr.status == 200) {
                    console.debug("Error code 200");
                }
                else {
                    currentData = {};
                    displayAjaxError(xhr.status);
                }
            }
        });

For some reason the error callback is called event though the http status code is 200 ie. the request is OK. Why is this?

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

The problem might be that the json data returned from the url is malformed. When the server actually returns something, the http status code is 200. But that doesn't mean that the data is proper json. Check that the stringified json data returned is correctly formed.

I'm answering my own guestion because I learned this the hard way. I hadn't escaped a "-quote character in my json data. This resulted in very odd behaviour. Luckily the double quote character is pretty much the only character that needs to be escaped from data delivered via JSON. (More on this issue: Where can I find a list of escape characters required for my JSON ajax return type?)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...