在函数内部调用时,XMLHttpRequest 未收到响应

XMLHttpRequest not receiving a response when called inside a function

我有一个 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。

似乎是什么问题?

如上述回复中所列,操作是重新呈现页面并终止请求。这将作为 onclick 函数处理程序或更改结构以使用 form 标记及其属性(如 [=18)调用它来完成=]动作和方法

通过 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>