JavaScript XMLHttpRequest using JsonP
For google api I was forced to add callback
and also v=1.0
parameter to url. Without v=1.0 parameter I get CORB error (for my version and also other answers code - however jQuery $.ajax
with dataType: "jsonp"
add this parameter - so I add it too and start working )
Cross-Origin Read Blocking (CORB) blocked cross-origin response https://ajax.googleapis.com/ajax/services/feed/load?callback=jsonp1555427800677 with MIME type text/javascript. See https://www.chromestatus.com/feature/5629709824032768 for more details.
Below is promise version of my solution
function jsonp(url) {
return new Promise(function(resolve, reject) {
var s = document.createElement('script');
var f="jsonp"+(+new Date()), b=document.body;
window[f] = d=>{ delete window[f]; b.removeChild(s); resolve(d); };
s.src=`${url}${url.includes('?')?'&':'?'}callback=${f}&v=1.0`;
b.appendChild(s);
})
}
async function send() {
let r = await jsonp("http://ajax.googleapis.com/ajax/services/feed/load");
console.log(r);
}
<button onclick="send()">Send JSONP</button>
I know you already got the answer for but if anyone else out here wanted an example of one using promises here's one.
function jsonp(url) {
return new Promise(function(resolve, reject) {
let script = document.createElement('script')
const name = "_jsonp_" + Math.round(100000 * Math.random());
//url formatting
if (url.match(/\?/)) url += "&callback="+name
else url += "?callback="+name
script.src = url;
window[name] = function(data) {
resolve(data);
document.body.removeChild(script);
delete window[name];
}
document.body.appendChild(script);
});
}
var data = jsonp("https://www.google.com");
data.then((res) => {
console.log(res);
});
JSONP does not use XMLHttpRequests.
The reason JSONP is used is to overcome cross-origin restrictions of XHRs.
Instead, the data is retrieved via a script.
function jsonp(url, callback) {
var callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random());
window[callbackName] = function(data) {
delete window[callbackName];
document.body.removeChild(script);
callback(data);
};
var script = document.createElement('script');
script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName;
document.body.appendChild(script);
}
jsonp('http://www.helloword.com', function(data) {
alert(data);
});
In interest of simplicity, this does not include error handling if the request fails. Use script.onerror
if you need that.