How to parse error and status message from serialize()?
I have this code
$(document).ready(function(){
// ...
$('form').submit(function() {
// ...
$.ajax({
type: "GET",
url: "/cgi-bin/ajax.pl",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: $(this).serialize(),
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('div#create_result').text(
"responseText: " + XMLHttpRequest.responseText +
", textStatus: " + textStatus +
", errorThrown: " + errorThrown);
$('div#create_result').addClass("error");
}, // error
success: function(result){
if (result.error) { // script returned error
$('div#create_result').text("result.error: " + result.error);
$('div#create_result').addClass("error");
} // if
else { // perl script says everything is okay
$('div#create_result').text(
"result.success: " + result.success +
", result.userid: " + result.userid);
$('div#create_result').addClass("success");
} //else
} // success
}); // ajax
$('div#create_result').fadeIn();
return false;
});
});
which always gives error messages, if it was successful.
Example:
responseText: Content-Type: application/json; charset=utf-8 {"success" : "Activity created", "Activity number" : "38"}, textStatus: par开发者_如何学JAVAsererror, errorThrown: SyntaxError: JSON.parse
Any ideas what is wrong?
Update:
Here is how I make the JSON strings in the server-side Perl script.
...
$json = qq{{"error" : "Owner $owner doesn't exist"}};
...
$json = qq{{"success" : "Activity created", "Activity number" : "$id"}};
...
print $cgi->header(-type => "application/json", -charset => "utf-8");
print $json;
This:
parseError,
SyntaxError: JSON.parse
Your response JSON is not acceptable to the parser, it might be malformed. Your posted responseText
has headers in it, those should NOT be present.:
Content-Type: application/json; charset=utf-8 {"success" : "Activity created", "Activity number" : "38"}
Consider using Perl's JSON module, which handles serialization and parsing for you. There is an XS backend (for speed), as well as a PP (Pure Perl) backend.
精彩评论