【问题标题】:JSON and AJAX, can't load, need JSONP? [closed]JSON 和 AJAX,无法加载,需要 JSONP 吗? [关闭]
【发布时间】:2017-07-17 17:43:09
【问题描述】:
function getJson(){
  $.ajax({
        type: "GET",
        url: "http://echo.jsontest.com/key/value/one/two",
        dataType: "json",
        success: function(data){
            alert("Success.");   
            //$('#bigdiv').append(JSON.stringify(data));
    },
        error: function (jqXHR, exception) {
        alert( jqXHR.status );
    }

  });
}

$("#start").click(function(){
  alert("check0");
  getJson();
});

https://codepen.io/anon/pen/PjvwPL

我被困在这里,为什么我不能从那个 URL 检索数据?

【问题讨论】:

  • 我希望这只是测试数据。它似乎包含密码,可能还包含医疗信息?
  • 不,那只是随机生成的信息

标签: javascript jquery json ajax


【解决方案1】:

您发布的 codepen 将不起作用(至少在 Chrome 中),因为 codepen 使用 https,但请求的资源是 http。但除此之外,您真正的问题可能是它是一个跨域请求,而您的服务器不允许这样做。

XMLHttpRequest cannot load https://zadanie.laboratorium.ee/users.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://s.codepen.io' is therefore not allowed access. The response had HTTP status code 502.

您可能需要在服务器端使用这样的标头才能使其正常工作:

Access-Control-Allow-Origin: https://calling-website.com
Content-Security-Policy: default-src 'self'; frame-ancestors https://calling-website.com

您可能需要更多。您可以在Google Developer Docs 中找到更多信息。

【讨论】:

    【解决方案2】:

    这是一个跨协议问题。

    Codepen 位于 https:// 网址上,因此 ajax 和 iframe 调用尝试使用该协议——但您的服务器没有配置 https,因此返回“502 Bad Gateway”错误。按照目前的配置,您的数据仅在纯 http://zadanie.laboratorium.ee/users.json URL 中可用。

    【讨论】:

      【解决方案3】:

      一些想法:查看cross origin policy

      此外,在使用 CodePen 时,请确保您的通话不会因为非 HTTPS 网址等原因而被阻止。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-02
        • 2019-12-03
        • 1970-01-01
        • 2015-01-18
        • 1970-01-01
        • 2013-01-10
        • 1970-01-01
        • 2014-06-11
        相关资源
        最近更新 更多