简体   繁体   中英

JSONP am I doing it right?

I have this in my main script ...

(function(d){
    var shortURLjs, id = 'shortUrl'; 
    if (d.getElementById(id)) {return;}
    shortURLjs = d.createElement('script'); 
    shortURLjs.id = id; 
    shortURLjs.async = true;
    shortURLjs.src = "http://site.com/test.js";
    d.getElementsByTagName('body')[0].appendChild(shortURLjs);
}(document));

And in test.js I have ...

shortURL = { "firstName": "John", "lastName" : "Smith"};

But when I try to access shortURL from within the script that included the test.js file after I added it, it's not defined.

I'm a little confused.

Your main function has to call something like, which will be added as a script tag to your head:

<script src="http://www.mydomain.com/file.php?callback=JSONP_callback"></script>

The callback=JSONP_callback , means that the JSONP_callback will be called within the javascript that returns the result. So your server knows which function to call to show the result. And on your mainpage, you have to define that function that handle the data.

function JSONP_callback(response)
{
    alert(response.name);
}

Then as you php or whatever scripting you use, you have to call the function from your callback, this can be anything as long as Javascript recognizes it:

// Within PHP it looks like:
echo $_GET['callback'] . "(" . json_encode(array( "name" => "Niels")) . ")";

// Which results in:
JSONP_callback({ name : "Niels" });

It results with that function name because we have called the page with the callback=JSONP_callback as parameter. And because we defined the function JSONP_callback(result) within our main page, the script will execute this function with the given data.

A few month ago I had to research this for school, the demo I made, maybe you can use it somehow: http://lutrasoft.nl/school/JSONP.html

The problem is that the script tag loads asynchronously so instead of things running like

insert tag
set shortURL
use shortURL
//your script finishes

the inserted script only has a chance to run after you are done

insert tag
use shortURL //oops!
//your script finishes
set shortURL

The trick behind JSONP is that instead of returning plain data we return what looks like a function call

//instead of setting a variable like "shortUrl = ..."
// we instead call a function:
on_have_shortUrl({"first_name":...});

so all you need to do is have a on_have_shortUrl function ready beforehand

function on_have_shortUrl(shortURL){ use shortURL here}
insert script tag
inserted script calls your function passing the data to it

Niel's answer goes on more detail about how the JSONP "protocol" lets you choose diferent names for the callback function and other things like that.

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