一:在接觸js項目的時候,會有一個疑問,爲什麼這些項目都要使用node.js來啓動項目,以服務形式去訪問(或者使用tomcat也可以)
以下轉自:https://www.cnblogs.com/lishanlei/p/10707853.html
關於在JS中AJAX導致跨域問題的解決
在部署一個原聲的前端項目的時候,請求該服務器後端接口時發現出現了CORS跨域的問題,但是服務端已經做了同源策略的兼容,常見問題,遂記錄。
報錯信息:
XMLHttpRequest cannot load http://xxxx.cn. Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https, chrome-extension-resource.
錯誤分析:
- 這是由於ajax的跨域訪問引起的
- ajax沒有經過服務器而直接訪問請求,使用了file協議
通俗的說,就是沒有在服務器環境中運行含有ajax方法的頁面,而是類似於瀏覽器直接打開的形式運行該頁面,這樣子並沒有使用http協議,而是直接使用了file協議。
本地頁面請求遠程服務端時,默認使用http://協議,但是本地頁面中的ajax方法請求本地時,默認的是file:///協議,而file協議是不予許跨域請求的,所以在請求時,請求的URL格式類似於:
http://xxxx.cn/xxxxx
在請求的url前一定要加上http://
二:js中讀取json文件,一般使用ajax方式,所以啓動項目需要使用node.js來啓動。
以下是關於json的讀取:轉自:https://blog.csdn.net/ClearLoveQ/article/details/90480207
1.首先編寫一個json文件:demo.json
[
{
"name":"張三",
"sex":"男",
"email":"[email protected]"
},
{
"name":"李四",
"sex":"男",
"email":"[email protected]"
},
{
"name":"王五",
"sex":"女",
"email":"[email protected]"
}
]
2.js讀取json文件
<script>
window.onload = function () {
var url = "demo.json"/*json文件url,本地的就寫本地的位置,如果是服務器的就寫服務器的路徑*/
var request = new XMLHttpRequest();
request.open("get", url);/*設置請求方法與路徑*/
request.send(null);/*不發送數據到服務器*/
request.onload = function () {/*XHR對象獲取到返回信息後執行*/
if (request.status == 200) {/*返回狀態爲200,即爲數據獲取成功*/
var json = JSON.parse(request.responseText);
for(var i=0;i<json.length;i++){
console.log(json[i].name);
}
console.log(json);
}
}
}
</script>
3.我的文件位置
4.用Ajax也是可以的
<script type="text/javascript">
var Ajax = function ()
{
$.getJSON ("demo.json", function (data)
{
$.each (data, function (i, item)
{
console.log(item.name);
});
});
}();
</script>
$.ajax({
url: "demo.json",//json文件位置,文件名
type: "GET",//請求方式爲get
dataType: "json", //返回數據格式爲json
success: function(data) {//請求成功完成後要執行的方法
//給info賦值給定義好的變量
var pageData=data;
for(var i=0;i<data.length;i++){
console.log(pageData[i].name);
}
}
})
————————————————
版權聲明:本文爲CSDN博主「ClearLoveQ」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/ClearLoveQ/article/details/90480207