简体   繁体   中英

JSONP Help (No jQuery)

I'm trying hard here to figure out how to do a JSONP request, but everywhere I look for reference material is all jQuery examples. I can read the jQuery source, but I wanted a clean and simple example. I'm building a library for something and I dont want to include jQuery, so please, no jQuery $.getJSON . I know how to do use that.

My server spits out the normal callback({"foo":"bar"}) response with a content-type: application/json; charset=utf-8 content-type: application/json; charset=utf-8 MIME.

So if I put in a script tag like (using Twitter since I KNOW their API works):

<script src="http://twitter.com/users/oscargodson.json?callback=test"></script>

Or dynamically. Either works and I get the JSON, its the next step I can't figure out.

If I do just console.log(test) after the script loads I get: Uncaught ReferenceError: test is not defined

Why? How, after i get the response from the server, do I then pass that to myself? On my own server if i do callback = {"foo":"bar"} callback works and returns an object, but not the way above. How come? Ive only used AJAX libraries to do this, but for this project I need to code it myself :)

If you set "callback=test", then in your client code you need to have a function called "test" that takes the json value from the server and handles it for you.

JQuery does just that, with a dynamically-generated function name.

function test(data) { console.log(data) }
get_jsonp("http://www.example.com/?callback=test")

A simple script inclusion should do the job:

function test(res) {
    // TODO: manipulate the results here like for example showing
    // the created_at property
    alert(res.created_at);    
}

window.onload = function() {
    var script = document.createElement("script");
    script.src = 'http://twitter.com/users/oscargodson.json?callback=test';
    document.body.appendChild(script);
};

And here's a live demo .

Obviously you shouldn't forget that browsers might cache static resources such as scripts so if you want to ensure fresh information you could adapt some timestamp to the url.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM