[英]JSONP am I doing it right?
我的主脚本中有这个...
(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));
在test.js中,我有...
shortURL = { "firstName": "John", "lastName" : "Smith"};
但是,当我尝试在添加了test.js文件的脚本中访问shortURL时,未定义它。
我有点困惑。
您的主要功能必须调用类似的东西,它将作为脚本标签添加到您的头部:
<script src="http://www.mydomain.com/file.php?callback=JSONP_callback"></script>
callback=JSONP_callback
,表示将在返回结果的javascript中调用JSONP_callback
。 因此,您的服务器知道要调用哪个函数来显示结果。 在主页上,您必须定义用于处理数据的函数。
function JSONP_callback(response)
{
alert(response.name);
}
然后,当您使用php或任何使用的脚本时,必须从回调中调用该函数,只要Javascript能够识别它,它就可以是任何东西:
// Within PHP it looks like:
echo $_GET['callback'] . "(" . json_encode(array( "name" => "Niels")) . ")";
// Which results in:
JSONP_callback({ name : "Niels" });
结果使用该函数名,因为我们已经使用callback=JSONP_callback
作为参数调用了该页面。 并且由于我们在function JSONP_callback(result)
定义了function JSONP_callback(result)
,因此脚本将使用给定的数据执行此函数。
几个月前,我不得不为学校进行研究,并进行了演示,也许您可以以某种方式使用它: http : //lutrasoft.nl/school/JSONP.html
问题是script标记是异步加载的,因此不会像
insert tag
set shortURL
use shortURL
//your script finishes
完成后,插入的脚本才有机会运行
insert tag
use shortURL //oops!
//your script finishes
set shortURL
JSONP背后的技巧是,我们返回的不是函数的纯函数,而是返回了普通的数据
//instead of setting a variable like "shortUrl = ..."
// we instead call a function:
on_have_shortUrl({"first_name":...});
所以您需要做的就是事先准备一个on_have_shortUrl
函数
function on_have_shortUrl(shortURL){ use shortURL here}
insert script tag
inserted script calls your function passing the data to it
Niel的答案提供了有关JSONP“协议”如何使您为回调函数选择不同名称以及其他类似内容的更多详细信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.