Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write JSONP Ajax request on pure js? [duplicate]

$.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?

like image 367
user2231356 Avatar asked May 16 '14 18:05

user2231356


People also ask

Can JSONP be used with AJAX?

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.

How do I create a JSONP request?

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.

What is JSONP in AJAX?

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.

Can JSONP execute JavaScript?

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.


2 Answers

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

like image 103
desu Avatar answered Oct 01 '22 17:10

desu


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);
like image 24
Kevin B Avatar answered Oct 01 '22 16:10

Kevin B