簡體   English   中英

XMLHttpRequest 在 function 內部調用時未收到響應

[英]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。

雖然,當我在 function 之外執行相同的代碼塊時 -

temp= new XMLHttpRequest();
temp.open('GET', 'url', true);
temp.onload = function () {
    console.log(temp.response);
    }
temp.send();
function getLocationTemp() {
console.log('random');
}

它有效,我得到數據和響應代碼為- 4。

我認為問題是流程離開了 function,因此本地加載超出了 scope。 所以嘗試在 function 中運行一個從 0-100 的 for 循環,認為它會給它足夠的時間來獲得響應,並且還放入一個在 readystate 變為 4 之前不會退出的 while 循環。但是 state 不會過去1.

似乎是什么問題?

如上述回復中所列,該操作是重新渲染頁面並終止請求。 這將作為onclick function 處理程序或更改結構以使用表單標記及其屬性(如actionmethod )調用它來完成。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM