Javascript and AJAX, only works when using alert()

前端 未结 9 1154
借酒劲吻你
借酒劲吻你 2020-12-01 15:01

I am having trouble with my javascript. It seems to be acting oddly. This is what\'s going on. I have a form, after the user submits it, it calls a function(onsubmit event)

9条回答
  •  不思量自难忘°
    2020-12-01 15:55

    The problem is that XMLHTTPRequest is asynchronous - it sends the request in the background and doesn't wait for it to finish.

    The alert statement causes the code to wait until the user clicks OK, during which the request finishes.

    You need to use the onreadystatechange event, like this:

    xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState==4) {
            // Do things
        }
    };
    

    The method you assign to this property will be called after the response is received. (and at other times, which is why you need to check that readyState is 4)

提交回复
热议问题