好吧,所以基本上我要做的是绕过JavaScript的跨域/same-Origin限制,以便我们可以在客户端网站的底部包含标语(托管的标语在我们的服务器上,可以在一个地方更新,而不是更新一百万个站点)。我想和JSONP在JQ中这样做。这是我的代码中显示标语的页面:
<div id="tagline"></div>
<script type="text/javascript">
$(document).ready(function() {
var url = "http://www.mydomain2.com/api/tagline.php";
$.getJSON(url + "?callback=taglineDisp", null, function(taglineDisp) {
for(i in taglineDisp) {
payload = taglineDisp[i];
$("#tagline").append(payload.text);
}
});
});
</script>
这是tagline.php的内容:
<?php header('Access-Control-Allow-Origin: *'); ?>
<?PHP echo "taglineDisp({"tagline" : "Powered by <strong><a href='http://www.mydomain2.com'>Company Name</a></strong>"}); ";
最初是tagline.php不是动态的,我只是有tagline.json。
taglineDisp({"tagline" : "Powered by <strong><a href='http://www.mydomain2.com'>Company Name</a></strong>"});
是的,对吗?JSONP需要具有taglinedisp();包裹在JSON对象上,是?
首先,我遇到了典型的原点限制错误,但是当我更改为.php并添加" access-control-wall-allow-Origin: *"标题指令时,我现在会得到:
Given URL is not allowed by the Application configuration.: One or more of the given URLs is not allowed by the App's settings. It must match the Website URL or Canvas URL, or the domain must be a subdomain of one of the App's domains. oauth:1
我希望我的描述和代码样本还可以。我已经阅读了有关Bajillion JSON文章(无论是在So还是在其他网站上),IBM实际上也有一些很棒的JSON资源用于JSON的内容),我仍然无法弄清楚我的位置。我主要是JQ菜鸟。:
这一切都值得吗?iframe会救我头痛吗?我认为JQ以跨浏览器兼容性而以某些额外的资源开销可能会更好。:|
您使用的是$ .getjson,因此您可以设置调用taglineDisp(json)
的回调。但是,如果您想使用JSONP,JavaScript方法有些不同!如果要动态加载JSONP,则应该执行以下操作:
function load_script(url) {
var s = document.createElement('script');
s.src = url;
document.body.appendChild(s);
}
function load_scripts() {
load_script('http://www.mydomain2.com/api/tagline.js');
}
window.onload=load_scripts;
如果要伪造复杂的JSONP,也可以使用:简单的JSON for php。
include('includes/json.php');
$Json = new json('callback', 'taglineDisp');
$Json->add('status', 200);
$Json->add('message', success);
$Json->add('tagline', "Powered by <strong><a href='http://www.mydomain2.com'>Company Name</a></strong>");
$Json->send();
更新:
您可以通过Getjson使用JSONP,只需发送JSON而没有回调
$.getJSON(
'http://www.mydomain2.com/api/tagline.js',
{'callback': 'process'}
);