简体   繁体   中英

JSON.parse SyntaxError: unable to correctly modify input (data)

Here is my code,

function rdsxsVal() {
'use strict';
$.get("../cgi-bin/csps_rdsxs.cgi?r=" + Math.random(), function (data) {

    spsVal = JSON.parse(data);

I use the debugger in Opera and see, data = "<?xml version="1.0" encoding=...

the error is: Uncaught SyntaxError: Unexpected token <

so I have researched a lot and tried what I can with no success.

JSON.parse('"ssdata"'); does not fail. This is not useful other than it confirms the format I need to correct the error. I need single quotes outside the double quotes.

So I tried adding single quotes by, data = "'" + data + "'"; but this results in,

data = "'<?xml version="1.0" encoding=...

which is wrong, the single quotes are in the wrong place.

I thought maybe the " (double quotes) was a debugger effect so used,

data = "" + data;

but this had no effect.

I also tried replacing the " with ' but this did not work,

data = data.toString().replace("\"", '\'');

I have a feeling there is a simple answer but I'm just not seeing it.

Solution: So by using the suggestion from @chris-vdp I now have the following working code and from the debugger I can confirm it enters the .done section and not the .fail even though both sections are the same for some reason.

function rdspsVal() {
'use strict';
$.ajax({
    url: "../cgi-bin/csps_rdsps.cgi?r=" + Math.random(),
    dataType: "xml"
}).done(function (data) {
    spsVal = data;
    if (!rdspsInit) {
        home();
        rdspsInit = true;
    }
    rdspsVal();
    timer1();
}).fail(function (data) {
    spsVal = data;
    if (!rdspsInit) {
        home();
        rdspsInit = true;
    }
    rdspsVal();
    timer1();
});

}

in place of the original,

function rdspsVal(){
$.get("../cgi-bin/csps_rdsps.cgi?r="+Math.random(), function(data) {
 spsVal = JSON.parse(data);
}).done(function(){
    if(!rdspsInit){
     home();
     rdspsInit = true;
    }
     rdspsVal();
     timer1();
}).fail(function(){
    if(!rdspsInit){
     home();
     rdspsInit = true;
    }
    rdspsVal();
    timer1();
});

}

$.get is shorthand for $.ajax . What you seem to be missing is the datatype. jQuery will parse your results for you.

$.ajax({
  url: "../cgi-bin/csps_rdsxs.cgi?r=" + Math.random(),
  success: success,
  dataType: "xml"
});

EDIT: example of assigning data to the variable using Promises.

$.ajax({
    url: "../cgi-bin/csps_rdsxs.cgi?r=" + Math.random(),
    dataType: "xml"
}).done(function(data) {
    spsVal=data;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM