2017-04-19 90 views
-1

獲取錯誤消息「XMLHttpRequest無法加載http://api.vateud.net/notams/warj.json。請求的資源上沒有'Access-Control-Allow-Origin'標頭Origin'http://run.plnkr.co 「因此不允許訪問」從外部URL獲取JSON數據並將其顯示在div中,但不工作

這裏是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> 
+1

你的選擇是錯誤的,我認爲。使用'$(「p」)。html(item.raw).appendTo(「。div」);' –

+0

我覺得問題與AJAX。你可以在javascript中使用XMLHttpRequest嘗試 – 2017-04-19 07:04:03

+0

@ Saik3037 - '$ .ajax'是XMLHttpRequest的一個包裝。 – Quentin

回答

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>

+0

是否有出路獲取網址的值?如果你可以提供示例代碼作爲出路? – januarsy

+0

@januarsy解決這個問題的唯一方法是使用JSONP,或者如果你擁有api域 - 你可以通過access-control-allow-origin頭文件。 –

+0

@januarsy實際上你可以發送請求到你的PHP服務器然後在api上找到curl並獲得響應並將其返回到頁面。 –

相關問題