[英]XMLHttpRequest not receiving a response when called inside a function
I have an HTML form that calls upon submitting, the function-我有一个在提交时调用的 HTML 表单,该函数-
function getLocationTemp() {
temp= new XMLHttpRequest();
temp.open('GET', 'url', true);
temp.onload = function () {
console.log(temp.response);
}
temp.send();
}
For some reason, I never receive a response to this API call.出于某种原因,我从未收到对此 API 调用的响应。 I have tried debugging the readyState, and i's always at- 1.
我试过调试 readyState,我总是在-1。
Although, when I execute the same block of code outside of the function as such-虽然,当我在 function 之外执行相同的代码块时 -
temp= new XMLHttpRequest();
temp.open('GET', 'url', true);
temp.onload = function () {
console.log(temp.response);
}
temp.send();
function getLocationTemp() {
console.log('random');
}
It works, I get the data, and response code as- 4.它有效,我得到数据和响应代码为- 4。
I assumed the issue was that the flow was leaving the function, and so the local onload was out of scope.我认为问题是流程离开了 function,因此本地加载超出了 scope。 So tried running a for loop from 0-100 within the function thinking it would give it enough time to get the response, and also put in a while loop that wouldn't exit until readystate became 4. But the state won't move past 1.
所以尝试在 function 中运行一个从 0-100 的 for 循环,认为它会给它足够的时间来获得响应,并且还放入一个在 readystate 变为 4 之前不会退出的 while 循环。但是 state 不会过去1.
What seems to be the issue?似乎是什么问题?
As listed in the above replies, the action is re-rendering the page and killing off the request.如上述回复中所列,该操作是重新渲染页面并终止请求。 This would be rather done as an onclick function handler or a change of the structure to call it using the form tag and its attributes like action and method .
这将作为onclick function 处理程序或更改结构以使用表单标记及其属性(如action和method )调用它来完成。
An example of doing this via the onclick method would be -通过 onclick 方法执行此操作的示例是 -
function getLocationTemp() {
temp= new XMLHttpRequest();
temp.open('GET', 'url', true);
temp.onload = function () {
console.log(temp.response);
}
temp.send();
}
and in the html something like this -在 html 中是这样的 -
<button type="button" onclick="getLocationTemp()">Submit Form</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.