好的,基本上我试图做的是绕过javascript的跨域/同源限制,以便我们可以在客户端站点的底部包含一个标语(在我们的服务器上托管,并且可以在一个地方,而不是更新一百万个网站)。我想用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-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的东西)我仍然无法弄清楚我哪里出错了。我主要是一个jq noob。 :\
这一切都值得吗?一个iframe会让我头疼吗?我认为jq可能更好的跨浏览器兼容性,但代价是额外的资源开销。 :|
答案 0 :(得分:1)
您正在使用$ .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,你也可以使用:Simple 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'}
);