JavaScript XMLHttpRequest using JsonP

I want to send request parameters to other domain

I already know that Cross Scripting needs JsonP and I have used JsonP with Jquery ajax

but i do not figure out how to do Cross Scripting as using XMLHttpRequest

following code my basic XMLHttpRequest code.

i guess i need to chage xhr.setRequestHeader() and i have to add parsing code

please give me any idea

var xhr;
function createXMLHttpRequest(){    
    if(window.AtiveXObject){
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        xhr = new XMLHttpRequest();
    }   
    var url = "http://www.helloword.com";   
}

function openRequest(){ 
    createXMLHttpRequest();
    xhr.onreadystatechange = getdata;
    xhr.open("POST",url,true);
    xhr.setRequestHeader("Content-Type",'application/x-www-form-urlencoded');
    xhr.send(data); 
}

function getdata(){
    if(xhr.readyState==4){
        if(xhr.status==200){
            var txt = xhr.responseText;
            alert(txt);
        }
    }   
}

Answers:

Answer

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.

Answer

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);
});
Answer
function JsonpHttpRequest(url, callback) {
    var e = document.createElement('script');
    e.src = url;
    document.body.appendChild(script); // fyi remove this element later /assign temp class ..then .remove it later
    //insetead of this you may also create function with  callback value and  use it instead
    window[callback] = (data) => {
        console.log(data);  // heres you data
    }
}
// heres how to use
function HowTouse(params) {
    JsonpHttpRequest("http://localhost:50702/api/values/Getm?num=19&callback=www", "www")
}
Answer

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>

Answer

You can not able to do Cross Scripting using XMLHttpRequest.If you want to cross domain with out Jquery, you must create a new script node and set the src attribute of it.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.