简体   繁体   中英

XMLHttpRequest not receiving a response when called inside a function

I have an HTML form that calls upon submitting, the function-

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. I have tried debugging the readyState, and i's always at- 1.

Although, when I execute the same block of code outside of the function as such-

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.

I assumed the issue was that the flow was leaving the function, and so the local onload was out of 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.

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 .

An example of doing this via the onclick method would be -

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 -

<button  type="button" onclick="getLocationTemp()">Submit Form</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM