JQuery 无法通过本地主机:8888 检索数据 drupal 服务


JQuery Unable to retrieve data drupal services through localhost:8888

我已经创建了一个服务,如本教程所述,我可以看到当我向浏览器键入此 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. 源 http://{本地主机}: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!");
    });
});

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

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

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

<?php 
    header('Access-Control-Allow-Origin: from-specific-domain.com');
?>

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

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 请求的文章