跨源資源分享 (CORS)
CORS 允許一個域上的網路應用向另一個域提交跨域 AJAX 請求。啟用此功能非常簡單,只需由伺服器發送一個響應標頭即可。
啟用 CORS 請求
假設您的應用已經在 example.com 上了,而您想要從 www.example2.com 提取資料。一般情況下,如果您嘗試進行這種類型的 AJAX 調用,請求將會失敗,而流覽器將會出現“源不匹配”的錯誤。利用 CORS,www.example2.com 只需添加一個標頭,就可以允許來自 example.com 的請求:
Access-Control-Allow-Origin: http://example.com
可將 Access-Control-Allow-Origin 添加到某網站下或整個域中的單個資源。要允許任何域向您提交請求,請設置如下:
Access-Control-Allow-Origin: *
參考:http://enable-cors.org/server.html
or simple CORS requests, the server only needs to add the following header to its response:
Access-Control-Allow-Origin: *
There are some more headers and settings involved if you want to support verbs other than GET/POST, custom headers, or authentication. You can learn more about these options in theUsing CORS tutorial on HTML5 Rocks.
If you want the TL;DR version, take a look at the flowchart for implementing CORS support.
If you'd like to learn more about implementing CORS for a specific platform, follow one of the links below:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<staticContent>
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
function loadjson() {
var xmlhttp = new XMLHttpRequest();
var url = "json/school.json";
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var jsonDoc = JSON.parse(xmlhttp.responseText);
myFunction(jsonDoc);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function myFunction(jsonDoc) {
document.getElementById("id01").innerHTML=jsonDoc[0].name;
document.getElementById("id02").innerHTML=jsonDoc[1].name;
document.getElementById("id03").innerHTML=jsonDoc[2].name;
//將json物件轉成string文字
txt01.value = JSON.stringify(arr);
}
//將json物件轉成string文字
txt01.value = JSON.stringify(jsonDoc);
var jsonDoc = JSON.parse(jsonstring);
txt01.value = JSON.stringify(jsonDoc);
[
{"ip":"http://www.tsu.edu.tw/","name":"台灣首府大學","address":"台南市麻豆區南勢里168號","tel":"06-5718888","pic":"icon80_80/image01.jpg"},
{"ip":"http://web.ncku.edu.tw/","name":"成功大學","address":"臺南市東區大學路1號","tel":"06-2757575","pic":"icon80_80/image02.jpg"},
{"ip":"http://www.nutn.edu.tw/","name":"台南大學","address":"台南市中西區樹林街二段33號","tel":"06-2133111","pic":"icon80_80/image03.jpg"},
{"ip":"http://www.feu.edu.tw/","name":"遠東科大","address":"台南市新市區中華路49號 ","tel":"06-5979566","pic":"icon80_80/image04.jpg"},
{"ip":"http://www.ksu.edu.tw/","name":"崑山科大","address":"台南市永康區崑大路 195 號","tel":"06-2727175","pic":"icon80_80/image05.jpg"},
{"ip":"http://www.stust.edu.tw/","name":"南台科大","address":" 台南市永康區南台街一號","tel":"06-2533131","pic":"icon80_80/image06.jpg"}
]