【发布时间】:2021-09-11 18:08:23
【问题描述】:
这是我的 js 代码:
var myreq=new XMLHttpRequest();
myreq.open("GET","https://<username>.github.io/test/data/data.json",true);
myreq.onload =function(){
console.log(JSON.parse(myreq.response));
}
myreq.send();
const data={
"name": "jayant",
"job": "leader"
};
function here()
{
var myreq1=new XMLHttpRequest();
myreq1.onload = () => {
// print JSON response
if (myreq1.status >= 200 && myreq1.status < 300) {
// parse JSON
const response = JSON.parse(myreq1.responseText);
console.log(response);
}
};
myreq1.open("POST",'https://<username>.github.io/test/data/data.json');
myreq1.setRequestHeader('Content-Type', 'application/json');
myreq1.send(JSON.stringify(data));
}
这里的函数是通过单击按钮调用的
这是我的 JSON 代码:
[
{
"name1":"jayant",
"age":58,
"pass":"LetsLearnJson"
},
{
"name1":"jayant2",
"age":45,
"pass":"ok"
},
{
"name1":"jayant3",
"age":24,
"pass":"test"
},
{
"name1":"abcd",
"age":75,
"pass":"abcd"
}
]
我在尝试发帖时收到此错误:
POST https://<username>.github.io/test/%22https://<username>.github.io/test/data/data.json%22 405
请帮忙。我已经尝试了很多网上已有的东西,但似乎没有任何效果
【问题讨论】:
-
XMLHttpRequest 是一个遗留 API,您应该尝试使用 Fetch api。 Link to fetch api
-
@SebastianCiocarlan - 使用 fetch 无法解决问题
-
@JaromandaX true 我应该在评论中也指出这一点。
-
meh @SebastianCiocarlan 我认为仍然使用 XHR 的人可能会被整个“承诺”的事情吓跑:
标签: javascript json post get xmlhttprequest