【问题标题】:Get JSON data from external URL and display it in a div, but not work [duplicate]从外部 URL 获取 JSON 数据并将其显示在 div 中,但不起作用 [重复]
【发布时间】:2017-04-19 17:44:30
【问题描述】:

收到错误消息“XMLHttpRequest 无法加载 http://api.vateud.net/notams/warj.json。请求的资源上不存在 'Access-Control-Allow-Origin' 标头。因此不允许访问源 'http://run.plnkr.co'”

这里是 plunker 链接:http://plnkr.co/edit/Kt340aO4WTYPb5sjCUDj?p=preview

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
    <div class="div"></div>

<script>

        $.ajax({
               type: "GET",
               url: "http://api.vateud.net/notams/warj.json",
               processData: true,
               data: {},
               dataType: "json",
               error: function(){ alert("Error"); },
               success: function (data) {
                   $.each(data, function(i,item){

                    $("<p>").html(item.raw).appendTo(".div");

                  });
               }
        });

</script>
</body>
</html>

【问题讨论】:

  • 我认为您的选择器是错误的。使用$("p").html(item.raw).appendTo(".div");
  • 我认为 ajax 有问题。您可以尝试在 javascript 中使用 XMLHttpRequest
  • @Saik3037 — $.ajax 是 XMLHttpRequest 的包装器。
  • “会有一条错误消息”——你设法说了六次,却没有告诉我们错误消息是什么。

标签: javascript html json ajax getjson


【解决方案1】:

错误是由于 CORS,即跨源请求,您会收到错误:

XMLHttpRequest cannot load http://api.vateud.net/notams/warj.json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

在此处阅读有关 CORS 的更多信息"No 'Access-Control-Allow-Origin' header is present on the requested resource" ..

同时在您的系统上运行下面的代码示例,您将在控制台中看到任何其他错误。

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="div"></div>
    
    <script>
    
            $.ajax({
                   type: "GET",
                   url: "http://api.vateud.net/notams/warj.json",
                   processData: true,
                   data: {},
                   dataType: "json",
                   error: function(e){
                    console.log(e);                    
                   },
                   success: function (data) {
                       $.each(data, function(i,item){
                        $(".div").append('<p>'+item.raw+'</p>');
                      });
                   }
            });
    
    </script>

【讨论】:

  • 有没有办法获取 url 的值??是否可以提供示例代码作为出路?
  • @januarsy 解决这个问题的唯一方法是使用 JSONP,或者如果您拥有 api 域 - 您可以传递 access-control-allow-origin 标头。
  • @januarsy 实际上,您可以向您的 PHP 服务器发送请求,然后向 api 发送一个 curl 以获取响应并将其返回到页面..
猜你喜欢
  • 2012-04-12
  • 2020-01-23
  • 1970-01-01
  • 2017-05-06
  • 2020-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-24
相关资源
最近更新 更多