[removed] How do I create JSONP?

2019-01-03 12:53发布

I have a two domains, example1.com and example2.com

From example1.com, I would like call a JSON API I have on example2.com. Knowing that this is not allowed, it occurred to me - this is exactly why JSONP was created.

Question is, how do I modify my JSON API to make it JSONP capable?

Basically, how do I create the callback api?

UPDATE

My server side language is PHP

8条回答
我命由我不由天
2楼-- · 2019-01-03 13:38
// Adds script tag to head of the page
function addScriptToHead(source, code, type) {
    var script = document.createElement('script');
    if (type === 'js') {
        script.setAttribute('type', 'text/javascript');
    }
    if (source !== '') {
        script.setAttribute('src', source);
    }
    if (code !== '') {
        if (document.all && !window.opera)  {
            script.text = code;
        } else {
            script.innerHTML = code;
        }
    }
    document.getElementsByTagName('head')[0].appendChild(script);
}


// Callback function
function addScriptToHead(any_param) {

// do whatever needs to be done

}

//call example

addScriptToHead('http://url_to_receiver_script/index.php&param=anything', '', 'js');

/// the callback script should return name of the Callback function, i.e. if you type in browser

http://url_to_receiver_script/index.php&param=anything

it should return just a text (name of existing processing function): addScriptToHead(any_param)

works like a clock in any browser.

查看更多
Explosion°爆炸
3楼-- · 2019-01-03 13:39

Easy with jQuery, that is the client side:

  $.ajax({
        dataType: 'jsonp',
        data: "somedata="+somevalue,
        //this is very important since it's the callback we will and that allow cross domain
        jsonp: 'jsonp_callback',
        url: 'http://example2.com',
        //function we trigger on success
        success: ParseJson
         //error handling not working with jsonP
         //error: handleError
        });

function ParseJson(data)
{
for (var key in data) {
  if (data.hasOwnProperty(key)) {
    alert(key + " -> " + data[key]);
  }
}
}

And be sure that you get proper json from the server side;
and don't forget to return the jsonp_callback param, otherwise it won't work!!!!!
and that's it really.

查看更多
登录 后发表回答