Traditional web interaction is that the user triggers an http request to the server, and then after the server receives it, it responds to the user and returns A new page, whenever the server processes a request submitted by the client, the client can only wait idle, and even if it is only a small interaction and only needs to get a simple piece of data from the server, a complete page must be returned. HTML page, and the user has to waste time and bandwidth to re-read the entire page every time. This approach wastes a lot of bandwidth. Since each application interaction requires sending a request to the server, the application's response time depends on the server's response time. This results in a user interface that is much less responsive than native apps.
The emergence of ajax just solves the shortcomings of traditional methods. AJAX is a technology for creating fast, dynamic web pages. AJAX enables web pages to update asynchronously by exchanging small amounts of data with the server in the background. This means that parts of a web page can be updated without reloading the entire page.
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <p id="showInfo"></p> <form id="form"> 用户名:<input type="text" name="username" id="username"/><br /> 密码:<input type="password" name="password" id="passowrd" /> <input type="button" value="提交" id="btn" /> </form> <script type="text/javascript"> window.onload=function(){ var btn=document.getElementById("btn"); btn.onclick=function(){ var username=document.getElementById("username").value; var password=document.getElementById("passowrd").value; var xhr=null; if(window.XMLHttpRequest){ xhr=new XMLHttpRequest(); }else{ xhr=new ActiveXObject('Microsoft.XMLHTTP'); } var url='new_file.php?username='+username+'&password='+password; xhr.open('get',url,true); xhr.onreadystatechange=function(){ if(xhr.readyState==4){ if(xhr.status==200){ var data=xhr.responseText; if(data==1){ document.getElementById("showInfo").innerHTML='提交失败'; }else if(data==2){ document.getElementById("showInfo").innerHTML='提交成功后'; } } } } xhr.send(null); } } </script> </body></html>
<?php //$username = $_GET['username']; //$password = $_GET['password'];$username=$_POST['username']; $password=$_POST['password']; if($username == 'admin' && $password == '123'){ echo 2; }else{ echo 1; } ?>
Note:
ajax request is Asynchronous request, so the third parameter of open should be set to true, but I tried to set it to false during the get request, that is, set it to a synchronous request, and still no error will be reported, but it is still recommended to set it to true: make an asynchronous request.
The above is the detailed content of How to implement Ajax GET POST request using native JS. For more information, please follow other related articles on the PHP Chinese website!