2

I am getting xhr response of a JSONP object similar to

JSONP({Objects})

This would pop an error if I do JSON.parse('JSONP({Objects})') (Unexpected token j in JSON at position 0), is there a JSONP.parse() function that will automatically strip *() from the JSONP response?

Why do I have to do this?

Because this JSONP response requires POST request, of which is to make it hard for other people to use it.

P.S., the callback padding JSONP is dynamic and unpredictable.

Aero Wang
  • 8,382
  • 14
  • 63
  • 99
  • 2
    You obviously don't know how JSONP works - see https://stackoverflow.com/questions/3839966/can-anyone-explain-what-jsonp-is-in-layman-terms – Jaromanda X Jun 10 '17 at 13:29
  • Are you sure the API doesn't support plain JSON as well? That would be really weird. – Bergi Jun 10 '17 at 13:57
  • @Bergi i don't think it is meant to be a public api – Aero Wang Jun 10 '17 at 15:16
  • @AeroWang Whatever API it is, I'm certain that they do not provide the JSONP format for the public and restrict the JSON format. Regardless what the case is, just ask the provider about a JSON API! – Bergi Jun 10 '17 at 17:26

1 Answers1

1

In theory you can still append the jsonp to the document by:

var jsonp = {};
function getList(callback){
  var xhrlist = new XMLHttpRequest();
  xhrlist.addEventListener('load',function(){
    if (xhrlist.status == 200) {
      callback(null, xhrlist.responseText);
    } else {
      console.log(xhrlist.responseText);
      callback('error');
    }
  });
  xhrlist.open('POST', 'http://example.com/');
  xhrlist.send('request=list');
}
getList((err, data)=>{
  if (err) {
    alert(err);
  } else {
    alert('success!');
    var script = document.createElement('script');
    script.innerHTML = data;
    document.getElementsByTagName('head')[0].appendChild(script);
  }
});
function JSONP(response) {
  jsonp = response;
}

Now there is a flaw here, function JSONP(response) must have the same name as your JSONP callback. So this is only valid if the callback stays the same, and you already know what it is.

Of course if you must strip JSONP you can try this:

data = data.substring(data.indexOf('(') + 1);
data = data.substring(0, data.length - 1);

In this case you don't need to know the callback.

James Wayne
  • 1,894
  • 14
  • 14