Reputation: 9217
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.
Upvotes: 2
Views: 350
Reputation: 1912
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.
Upvotes: 1