$.ajax( { url : '', data: {}, dataType:'jsonp', jsonpCallback: 'callbackName', type: 'post'
,success:function (data) {
console.log('ok');
},
error:function () {
console.log('error');
}
});
How do I write the same functionality in pure JS?
Google Sheets as JSON data source for JavaScript According to the AJAX model, web applications can send and retrieve data from a server asynchronously without interfering with the display and the behavior of the existing page. Many developers use JSON to pass AJAX updates between the client and the server.
Method to use JSONP:In HTML code, include the script tag. The source of this script tag will be the URL from where the data to be retrieve. The web services allow to specify a callback function. In the URL include the callback parameter in the end.
JSONP stands for JSON with Padding. Requesting a file from another domain can cause problems, due to cross-domain policy. Requesting an external script from another domain does not have this problem. JSONP uses this advantage, and request files using the script tag instead of the XMLHttpRequest object.
It was proposed by Bob Ippolito in 2005. JSONP enables sharing of data bypassing same-origin policy, which disallows running JavaScript code to read media DOM elements or XMLHttpRequest data fetched from outside the page's originating site.
var xmlhttp=new XMLHttpRequest();
xmlhttp.open("POST", 'http://forexplay.net/ajax/quotes.php');
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if(xmlhttp.status == 200){
console.log('Response: ' + xmlhttp.responseText );
}else{
console.log('Error: ' + xmlhttp.statusText )
}
}
}
xmlhttp.send(data);
I'm always forgetting about capital and small letters in XMLHttpRequest
In this particular case, you aren't making an ajax call at all, instead you're making a JSONP request. Luckily, these are incredibly easy to replicate and work in all browsers.
var s = document.createElement("script"),
callback = "jsonpCallback_" + new Date().getTime(),
url = "http://forexplay.net/ajax/quotes.php?callback=" + callback;
window[callback] = function (data) {
// it worked!
console.log(data);
};
s.src = url;
document.body.appendChild(s);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With