Javascript and AJAX, only works when using alert()

前端 未结 9 1172
借酒劲吻你
借酒劲吻你 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:47

    You're sending the request asynchronously, because of this:

    xmlhttp.open(..., true);
    

    Passing true as the third argument to open() means that the code will continue to run before the result comes back.

    The alert() is giving that asynchronous request time to complete before the subsequent code runs.

    I'd normally recommend moving all the code that depends on the result of the AJAX call into the callback, within the:

    if(xmlhttp.readyState == 4)
    

    block, but in your case you need the result of the call to know what to return from your validation function. In that case, you're going to have to use a synchronous call, by passing false to open(). Then your subsequent code won't run until the response has come back.

提交回复
热议问题