javascript – jquery ajax调用返回错误与readystate 4,状态200,statustext ok

前端之家收集整理的这篇文章主要介绍了javascript – jquery ajax调用返回错误与readystate 4,状态200,statustext ok前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这真让人难以置信.我从ajax收到错误回调.但是,如果我从错误消息中获取res.responseText(返回正确,顺便说一句)并使用它,它就做对了.就像我收到了成功回调一样.

数据设置如下:

var dataToSend = {fieldname : textdata};

和ajax调用是这样的:

var ajaxOptions = {
    url: '/newpage',data: JSON.stringify(dataToSend),contentType: 'application/json; charset=utf-8',dataType: 'json',cache: false,processData: false,type: 'POST',success: function(res) {
        console.log("success!");
        $('#' + divname).html(res);
    },error: function(res) {
        console.log("There was an error: " + JSON.stringify(res));
        $('#' + divname).html(res.responseText);
    }
};

$.ajax(ajaxOptions);

错误消息是:出现错误:{“readyState”:4,“responseText”[此部分完全正常],“status”:200,“statusText”:“OK”}.

解决方法

如果您的responseText不是正确的JSON,则会引发解析错误.确保您的响应是有效的JSON或删除dataType:“json”.

jQuery docs开始:

dataType (default: Intelligent Guess (xml,json,script,or html))

Type: String

The type of data that you’re expecting back from the server. If none
is specified,jQuery will try to infer it based on the MIME type of
the response (an XML MIME type will yield XML,in 1.4 JSON will yield
a JavaScript object,in 1.4 script will execute the script,and
anything else will be returned as a string). The available types (and
the result passed as the first argument to your success callback) are:

“json”: Evaluates the response as JSON and returns a JavaScript object. Cross-domain “json” requests are converted to “jsonp” unless the request includes jsonp: false in its request options. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9,an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.)

猜你在找的Ajax相关文章