簡體   English   中英

無法從URL加載JSON數據並以HTML顯示

[英]Having trouble loading JSON data from URL and displaying in HTML

我正在嘗試創建一個HTML / JavaScript程序,該程序讀取外部JSON文件(通過URL),然后以列出的順序將它們輸出到網頁。

我已經為此工作了好幾天,但似乎無法克服Internet Explorer控制台中彈出的錯誤。 錯誤是:

SEC7120:在Access-Control-Allow-Origin標頭中找不到源(我的Azure Web應用URL)。 (我的程序名稱)

SCRIPT7002:XMLHttpRequest:網絡錯誤0x80700013,由於錯誤80700013而無法完成操作。

我能夠讀取第一個URL並通過'console.log(data)'在控制台中讀取,但這僅是因為它與我的代碼位於同一原始域中。 兩者都在我的Azure webapp git目錄中。 如何通過URL通過其他外部JSON文件訪問? 我必須從自己的網絡應用程序中讀取所有同學。 任何幫助將不勝感激,我在這里真的受了苦。 我有一種需要使用JSONp的感覺,因此使用$ .ajax()而不是$ .getJSON()。 我正在使用JQUERY。 我的代碼:

<!DOCTYPE html>
<html>
<head>
</head>

<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Klump Test</h1>
<p><input onclick="AddStudent()" type="button" value="Add Student"/></p>

<script>
var urls = ["https://michael-pedzimaz-webapp.azurewebsites.net/my-information.json",
            "https://jakeisalsoclueless.azurewebsites.net/myinformation.json",
            "https://riotjuice.azurewebsites.net/my-information.json",
            "https://softwareengjmh.azurewebsites.net/format.JSON",
            "https://newtestdocument.azurewebsites.net/Format.json"];

function AddStudent(){
    var person = prompt("Please enter your json url:", "");
    //var _person = person + '?callback=?';
    getJson(person);
 }
</script>

<input onclick="getJson(urls[0])" type="button" value="Mike's JSON"/>
<input onclick="getJson(urls[1])" type="button" value="Jake's JSON"/>
<input onclick="getJson(urls[2])" type="button" value="Julian's JSON"/>
<input onclick="getJson(urls[3])" type="button" value="Jace's JSON"/>
<input onclick="getJson(urls[4])" type="button" value="Thad's JSON"/>

<div class="mypanel"></div>

<script>
function getJson(url){
    $.getJSON(url, function(data){
        console.log(data);
        var info = 'First name: ${data.FirstName}<br> Last Name: ${data.LastName}<br> Preferred Name: ${data.PreferredName}<br> Team Name: ${data.TeamName}<br> Seat Location: ${data.SeatLocation}<br> Role: ${data.Role}<br>'

        $(".mypanel").html(info);
    });
}
</script>
</body>
</html>

如何格式化所有JSON文件:

{
"FirstName":"Michael",
"LastName":"Pedzimaz",
"PreferredName":"Mike",
"TeamName":"The Ocelots",
"SeatLocation":"1-2",
"Role":["UI Designer"]
}

感謝您的任何幫助。

您所需要的就是jsonp,這是對的,但是,您所請求的服務器需要支持jsonp才能真正了解?callback URL參數。

azurewebsite.net將需要支持CORS(添加其他標頭以讓您獲取JSON)或jsonp。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM