json data, but I get a SyntaxError?
Here is a code fragment from a page:
$("#add_new").button().click(function (ui,event) {
var postdata = {
"action":"new",
field_kind_id:2,
collection_id:null,
parent_id:null,
app_struct_id:null,
member_id:1033,
app_id:1003,
};
$.ajax({
url: "?",
type: "POST",
data: postdata,
error: function(jqXHR, textStatus, errorThrown) {
$().toastmessage("showErrorToast",
"AJAX call failed: "+textStatus+" "+errorThrown);
},
success: function(data) {
edit_record(data);
return false;
}
});
});
Actually the POST-ed data is something like:
action new
app_id 1003
app_struct_id null
collection_id null
field_kind_id 2
member_id 1033
parent_id null
And the response is this string:
{x22app_idx22:1003,x22member_idx22:1033,x22collection_idx22:x22-6885x22,x22field_kind_idx22:2,x22sample_idx22:x22x22,x22parent_idx22:x22x22}
The response is not valid json data. It has a special format. My problem is that the above ajax call displays this toast message:
"AJAX call failed: parsererror SyntaxError: illegal character"
So it seems that the AJAX call has failed. But I don't understand what is checking the syntax? What kind of syntax? The JQuery Ajax call did not have "dataType:json" specified. So there should not be any syntax to be checked. What am I missing?
The JQuery documentation says the default value for "dataType" is "intelligent"
"Intelligent Guess (xml, json, script, or html)"
If the response cannot be interpreted as a JSON value, then it is not a JSON value, right? Either it is not a valid JSON value (in that case, it should not be converted) or it is (but then it should not throw an exception?) Does it mean that jQuery is not intelligent enough?
What is the value of the Content-Type header in the response from the server? I would expect any guessing that is performed regarding the format of the content to be based on that.
I suggest you explicitly set the dataType
to "text"
(see jQuery.ajax), so that jQuery does not need to guess the response's content type:
$.ajax({
url: "?",
type: "POST",
data: postdata,
dataType: "text", // the type of data that you're expecting back from the server
error: function(jqXHR, textStatus, errorThrown) {
$().toastmessage("showErrorToast",
"AJAX call failed: "+textStatus+" "+errorThrown);
},
success: function(data) {
edit_record(data);
return false;
}
});
The reason for the error you encounter is probably the following: jQuery assumes your server's response is in JSON format and tries to parse it.
链接地址: http://www.djcxy.com/p/48172.html上一篇: 在嵌套的ajax调用中获取JSON