我有一个HTML表单,该表单在提交时会调用-
function getLocationTemp() {
temp= new XMLHttpRequest();
temp.open('GET', 'url', true);
temp.onload = function () {
console.log(temp.response);
}
temp.send();
}
由于某种原因,我从未收到对此API调用的响应。我尝试调试readyState,但我始终处于-1。
尽管如此,当我在函数外部执行相同的代码块时,例如
temp= new XMLHttpRequest();
temp.open('GET', 'url', true);
temp.onload = function () {
console.log(temp.response);
}
temp.send();
function getLocationTemp() {
console.log('random');
}
它有效,我得到数据,并且响应代码为-4。
我认为问题是流程离开了函数,因此本地加载超出了范围。因此尝试在函数中从0到100运行一个for循环,以为它会给它足够的时间来获取响应,并放入一个while循环,直到readystate变为4时,该循环才会退出。 但是状态不会超过1。
似乎是什么问题?
答案 0 :(得分:1)
如以上答复中所列,该操作是重新呈现页面并终止该请求。宁可作为 onclick 函数处理程序,也可以更改结构以使用 form 标签及其属性(如 action 和方法。
通过onclick方法执行此操作的示例为-
function getLocationTemp() {
temp= new XMLHttpRequest();
temp.open('GET', 'url', true);
temp.onload = function () {
console.log(temp.response);
}
temp.send();
}
以及类似html的
<button type="button" onclick="getLocationTemp()">Submit Form</button>