admin管理员组

文章数量:1401444

I am making an ajax call

$.ajax({
   url: 'url',
   data: {},
   method: 'POST',
   enctype: 'multipart/form-data',
   dataType: 'json',
   success: function(data){
      // handle success
   },
   error: function(data, textStatus){
       //handle error
   }
});

Here my json response is

{
    person: {
        name: 'John'
    }

As you can see, the json response is not well formed. Hence I get the error

json parse error: Expected '}'

in the

error: function(data, textStatus){

}

How, can i ignore this parse error and continue with my executing since I have received the response.

I am making an ajax call

$.ajax({
   url: 'url',
   data: {},
   method: 'POST',
   enctype: 'multipart/form-data',
   dataType: 'json',
   success: function(data){
      // handle success
   },
   error: function(data, textStatus){
       //handle error
   }
});

Here my json response is

{
    person: {
        name: 'John'
    }

As you can see, the json response is not well formed. Hence I get the error

json parse error: Expected '}'

in the

error: function(data, textStatus){

}

How, can i ignore this parse error and continue with my executing since I have received the response.

Share Improve this question asked Nov 5, 2014 at 1:21 user544079user544079 16.6k42 gold badges120 silver badges172 bronze badges 0
Add a ment  | 

2 Answers 2

Reset to default 6

You can't ignore a parser error. With a parser error, no data has been parsed. Fix your data.

If you cannot fix your data server-side, get a better data source. If you cannot do that and you must fix it client side, concatenate a } on there, then parse manually (disable jQuery parsing), and hope that your entire system doesn't e crumbling down when someone fixes their bug later (which is inevitable).

From @squint:

Don't request JSON or send JSON response headers and jQuery won't parse it.

What this means is that you're requesting JSON with dataType: 'json'. Use text instead. More info in the jQuery docs: http://api.jquery./jquery.ajax/

You can think of the success/error methods in a jQuery ajax call as messengers - messengers to you, in a sense.

If the success method is invoked, the server gave you good data, which you handle in the ensuing function. If the error method is invoked, the server gave you bad data. You could still potentially handle the data within the error method, but the problem is that it's bad data (think of it as unreliable, if you will). If data is unreliable, it is bad programming technique to try to amend bad data within your code by making acmodations.

As a programmer, you want to always pursue good data - so the point here is to get good data from the remote server so that the success method will be invoked, not the error. Does this make sense?

本文标签: javascriptjson parse error Expected 3939Stack Overflow