Javascript-ajax: How do I get the return value of a function called by onreadystatechange?

Source: Internet
Author: User
Keywords javascript php
Here's CheckName () W Why can't I expect the return value (True/false), how to get the return value of Chekname (), on the basis of using AJAX? Seek the expert's guidance,
Just started to learn how to use Ajax for forms validation; I don't know how to solve this problem.
, the contents of the form are like this, here are a few of the main validation functions,

function CheckName () {var name=ele.name.value;                if (name!= "") {xmlhttp=new XMLHttpRequest ();                    Url= "http://localhost/chkname.php"; Xmlhttp.onreadystatechange =function () {if (xmlhttp.readystate = = 4) {if (Xmlhttp.status =                        = $) {var msg = Xmlhttp.responsetext;                              if (msg = = ' 1 ') {ele.name.classname= "";//Remove Class Ele.imgs[0].setattribute ("src", "img/right.jpg"); corresponding icon Ele.imgs[0].style.display = "inline";                        Show return true;                              }else{ele.name.classname= "borderred";//Remove Class Ele.imgs[0].setattribute ("src", "img/wrong.jpg"); corresponding icon Ele.imgs[0].style.display = "inline";                  Show                 biaoqian1.innerhtml= ' the user name already exists';                                                                                                   return false;            }}}} xmlhttp.open (' POST ', url,true);                Xmlhttp.send (NULL); } function Check () {//form submission validates the start if (CheckName () &&checkpassw2 () &&checkemail ()) {alert (  "Registered success");           Registration successful return true; } else{alert ("Please fill out the correct information!")            ");          return false; }    }

Reply content:

Here's CheckName () W Why can't I expect the return value (True/false), how to get the return value of Chekname (), on the basis of using AJAX? Seek the expert's guidance,
Just started to learn how to use Ajax for forms validation; I don't know how to solve this problem.
, the contents of the form are like this, here are a few of the main validation functions,

function CheckName () {var name=ele.name.value;                if (name!= "") {xmlhttp=new XMLHttpRequest ();                    Url= "http://localhost/chkname.php"; Xmlhttp.onreadystatechange =function () {if (xmlhttp.readystate = = 4) {if (Xmlhttp.status =                        = $) {var msg = Xmlhttp.responsetext;                              if (msg = = ' 1 ') {ele.name.classname= "";//Remove Class Ele.imgs[0].setattribute ("src", "img/right.jpg"); corresponding icon Ele.imgs[0].style.display = "inline";                        Show return true;                              }else{ele.name.classname= "borderred";//Remove Class Ele.imgs[0].setattribute ("src", "img/wrong.jpg"); corresponding icon Ele.imgs[0].style.display = "inline";                  Show                 biaoqian1.innerhtml= ' the user name already exists';                                                                                                   return false;            }}}} xmlhttp.open (' POST ', url,true);                Xmlhttp.send (NULL); } function Check () {//form submission validates the start if (CheckName () &&checkpassw2 () &&checkemail ()) {alert (  "Registered success");           Registration successful return true; } else{alert ("Please fill out the correct information!")            ");          return false; }    }

Async Ajax actually uses a separate process, so it can't get to the return value, and you don't know when to call the Ajax () method when it's done. So for asynchronous Ajax, you can't take the initiative to get its return value, you can only provide a callback method, the Ajax object can pass parameters to the callback method you provide, such as above, you get the return value through the callback function.

 //ajax验证name
var ajaxresult = false;//global variable function ajaxresultdeal (response) {Ajaxresult = response;//pass to global variable                                  if (Ajaxresult = = ' 1 ') {ele.name.classname= "";//Remove Class Ele.imgs[0].setattribute ("src", "img/right.jpg"); corresponding icon Ele.imgs[0].style.display = "inline";                                  Display ajaxresult= true;                                  } else{ele.name.classname= "borderred";//Remove Class Ele.imgs[0].setattribute ("src", "img/wrong.jpg"); corresponding icon Ele.imgs[0].style.display = "inline"; Show Biaoqian1.innerhtml= 'the user name already exists';                                                                                                               Ajaxresult=false;                       } ajaxresultreturn ();        } function Ajaxresultreturn () {if (Ajaxresult) {return true;}        else{return false;                    }} function Toajax (url,callback) {xmlhttp=new XMLHttpRequest (); /*url= "http://localhost/chkname.php";                        */Xmlhttp.onreadystatechange =function () {if (xmlhttp.readystate = = 4) {                                   if (Xmlhttp.status = =) {if (callback) {                                                      Callback (Xmlhttp.responsetext);    }}}} xmlhttp.open (' POST ', url,true);            Xmlhttp.send (NULL);            } function CheckName () {var name=ele.name.value;              var url= "http://localhost/chkname.php";                       var cb = Ajaxresultdeal;                                      Toajax (URL,CB);               } function Check () {//form submission validates the start if (Ajaxresultreturn () &&checkpassw2 () &&checkemail ()) {  Alert ("Registered success");           Registration successful return true; } else{alert ("Please fill out the correct information!")            ");          return false;       }    }

The first floor is very detailed. The reason for using AJAX is because of asynchronous loading, which requires you to change your mind and not write asynchronous code in a synchronous way.
Give you a classic logic to help you get started.

function beforeAjax() {    //一些基础的工作,比如非空验证,获得url,参数字符串等    doAjax();}function doAjax() {    var ajax = new Ajax;//这是伪码    ajax.onSuccess = afterAjax; //这是伪码,可能是onSuccess, onReadyStatusChange等任何事件,只要你的ajax对象支持的就行。    ajax.send();}function afterAjax(param1, param2, etc...) {    //后续的处理}

This is the three-step approach to the asynchronous code model, first prepare, and then start the asynchronous processing, we do not know when asynchronous processing will be completed, so what can be done is to tell the asynchronous processing object, when the XX event, please call the XX method.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.