【问题标题】:JSON/JSONP/PHP Headache D:JSON/JSONP/PHP 头痛 D:
【发布时间】:2012-10-07 23:01:41
【问题描述】:

好的,所以基本上我要做的是绕过 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 菜鸟。 :\

所有这些工作都值得吗? iframe 会不会让我头疼?我认为 jq 可能会更好地实现跨浏览器兼容性,但代价是一些额外的资源开销。 :|

【问题讨论】:

  • 我很想使用&lt;div id="tagline"&gt;&lt;script src="http://www.mydomain2.com/api/tagline.js"&gt;&lt;/script&gt;&lt;/div&gt;
  • 嗯,这就是我最初所做的,但有人建议我使用 JSONP 对象,而不仅仅是包含外部 javascript。我猜你的方法要简单一百万倍。 :|

标签: json cross-domain jsonp same-origin-policy cross-domain-policy


【解决方案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'}
);

【讨论】:

    猜你喜欢
    • 2014-01-07
    • 1970-01-01
    • 2012-07-29
    • 1970-01-01
    • 1970-01-01
    • 2010-12-14
    • 2010-11-08
    • 2012-09-07
    • 2015-09-18
    相关资源
    最近更新 更多