简体   繁体   中英

Use response of XMLHttpRequest

I'm new in JS and I'm trying to create a function that check something before submit a form. On html I have:

<form name="loginform" method="post" onsubmit="return foo()" action="adminlogin.php"> ... </form>

The function foo() is:

foo(){
  if(..){
  return false;
  }
  else{
        var url = "credenziali.php";
        var params = "name="+username+"&password="+password;
        var http_r = new XMLHttpRequest();
        http_r.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                //something
            }
        };
        http_r.open("GET", url+"?name="+username+"&pass="+password, true);
        http_r.send();
        // here I want to return false or true dependence of responseText
    }

the comment in the function is where I want use the what the request returns. How can I do?

Try insert this before http_r.send() with your return inside.

 http_r.onload = function() { if (http_r.status >= 200 && http_r.status < 400) { // Success! } else { // We reached our target server, but it returned an error } }; 

改用JQuery AJAX ... http://api.jquery.com/jquery.ajax/更为简洁。

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