Javascript: Unexpected token ILLEGAL
I have the error Uncaught SyntaxError: Unexpected token ILLEGAL
in Chrome.
The code is
$("form#new_redemption").live('submit', function() {
event.preventDefault();
var that = $(this);
var action = that.attr('action');
var data = that.serialize();
$.ajax({
type: "POST",
url: action,
data: data,
dataType: 'json',
beforeSend: function(request) {
request.setRequestHeader("Accept", "application/json");
},
success: function(res) {
var response = JSON.parse(res.responseText); // <~~~ Unexpected token ILLEGAL
if (response.message) {
that.slideUp();
$("#results").html(response.message).attr('class', 'notice').slideDown();
}
else if (response.url) {
window.location = response.url
}
},
error: function(res) {
var response = JSON.parse(res.responseText);
$('#results').html(response.error).attr('class', 'error').slideDown();
}
});
return false;
});
On errors, this code works great. But every time its a successful response I get an error. Is there a proble开发者_Go百科m here? And is there a way in VIM to highlight illegal javascript characters in the code?
Thank you!
Setting dataType
to json
will automagically parse the response JSON for you within the success
callback.
Try this:
$("form#new_redemption").live('submit', function() {
event.preventDefault();
var that = $(this);
var action = that.attr('action');
var data = that.serialize();
$.ajax({
type: "POST",
url: action,
data: data,
dataType: 'json',
beforeSend: function(request) {
request.setRequestHeader("Accept", "application/json");
},
success: function(res) {
if (response.message) {
that.slideUp();
$("#results").html(response.message).attr('class', 'notice').slideDown();
}
else if (response.url) {
window.location = response.url
}
},
error: function(res) {
var response = JSON.parse(res.responseText);
$('#results').html(response.error).attr('class', 'error').slideDown();
}
});
return false;
});
To expand on one of the comments above, I was getting this error because of a problem in the JSON results that were being returned. Specifically, one of the string values in the JSON response data had an unescapted double quote in it. In my case, it was my own Ajax function that I was calling, so what I did to fix it was to escape the double quotes on the server before returning the JSON data. Then I discovered that I had the same problem with newline characters, so I used a str_replace call that I found in another post: PHP's json_encode does not escape all JSON control characters
function escapeJsonString($value) {
# list from www.json.org: (\b backspace, \f formfeed)
$escapers = array("\\", "/", "\"", "\n", "\r", "\t", "\x08", "\x0c");
$replacements = array("\\\\", "\\/", "\\\"", "\\n", "\\r", "\\t", "\\f", "\\b");
$result = str_replace($escapers, $replacements, $value);
return $result;
}
精彩评论