[英]XHR calls return empty
我是AJAX的新手,我正在嘗試調用json文件,但在控制台中未返回任何內容。 我查看了“網絡”標簽,其xhr狀態為200。
const xhr = new XMLHttpRequest();
xhr.readyState = function(){
if(xhr.readyState === 4){
console.log(xhr.responseText)
}
}
xhr.open('GET','data/task.json');
xhr.send();
和task.json是
{
"jobs": [
{
"id": 7,
"title": "Clerk",
"employer": {
"name": "AOL"
},
"location": "Floria",
"salary": "$45k+"
}
]
}
我嘗試解析它並使用控制台將其打印出來,但控制台也為空。
您在發出的請求中有幾點需要注意。
您需要將status
添加到200
因為它是OK狀態。 意思是您的請求通過了。 因此,該部分將完全變為(this.readyState == 4 && this.status == 200)
。
您還需要從使用三等號===
更改為==
因為您沒有按TYPE進行比較,因為JS中使用了三等號。
使用事件處理程序xhttp.onreadystatechange
而不是xmr.readySate
。 這是Mozilla文檔的鏈接 。
所以它應該變成:
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange= function(){
if(xhttp.readyState === 4 && xhttp.status == 200){
console.log(xhr.responseText)
}
}
xhr.open('GET','data/task.json');
xhr.send();
這是W3Schools 文檔中包含example的詳細文檔。
您需要onreadystatechange
不是readyState
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
console.log(xhr.responseText)
}
}
xhr.open('GET','data/task.json');
xhr.send();
您應該使用xhr.onreadystatechange代替xhr.readyState,例如:xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
console.log(xhr.responseText)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.