Detailed explanation of JavaScript solving parsererror error case in ajax

  • 2021-11-13 00:32:50
  • OfStack

The ultimate solution to the parsererror error of ajax (json problem of data passed from background to foreground)

The reason for this problem is that there is a problem with the data passed from the background to the foreground. ajax is particularly strict with the format of json

The following is an ajax request with this problem


$.ajax({
type:'get',
url:"{php echo $this->createWebUrl('ajax',array('ac'=>'cunByXiangId'))}",
data:{id:id},

    dataType:'json',// This place is the crux of the problem 

    success:function(obj){

},error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(textStatus);
}
});

The main problem is dataType: 'json', this line of code, which means that the data received and returned is in json format. At this point, we just need to delete this code, and we will receive the string format

Data, and then convert it into json format, the following is the code


$.ajax({
type:'get',
url:"{php echo $this->createWebUrl('ajax',array('ac'=>'cunByXiangId'))}",
data:{id:id},
success:function(obj){
obj=eval('('+obj+')');// This code converts the string into a json Format 
},error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.status);
alert(XMLHttpRequest.readyState);
alert(textStatus);
}
});

Related articles: