0

正如本教程所说,我已经创建了一个服务,当我在浏览器中输入这个 url 时,我可以看到:

http://{localhost}:8888/drupal2/test_test/node/1.jsonp

或者

http://{localhost}:8888/drupal2/test_test/node/1.json

或者

http://{localhost}:8888/drupal2/test_test/system/connect.json

我得到了 json 回调。但是当它在 jquery 代码中时,我得到

XMLHttpRequest 无法加载 http://{localhost}:8888/drupal2/test_test/node/1.json?type=post&format=json。Access-Control-Allow-Origin 不允许来源 http://{localhost}:8383。

为什么会这样?

jQuery 代码:

$(function() {
    var urlis = "http://localhost:8888/drupal2/test_test/node/1.json";
    $.getJSON(urlis, {
        type: 'post', 
        format: "json"
        }).done(function(afterdone) {
        console.log("JSONP Data");
    })
     .fail(function(error) {
        console.log("NO!");
    });
});
4

2 回答 2

1

您需要允许跨域 AJAX。要在 PHP 中执行此操作,请修改脚本:

header('Access-Control-Allow-Origin: domain.com');

或修改您的 htaccess 或 apache conf 文件:

<FilesMatch "\.*$">
  <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "domain.com"
  </IfModule>
</FilesMatch>

另外,看看这篇关于带有 JSON 响应的跨域 AJAX 请求的文章

于 2013-09-26T15:34:46.520 回答
1

在您的服务器上添加响应标头:

Access-Control-Allow-Origin: from-specific-domain.com

你也可以用 php 做到这一点:

<?php 
    header('Access-Control-Allow-Origin: from-specific-domain.com');
?>
于 2013-09-26T15:35:12.853 回答