表单页面(使用了get方法)
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>原生ajax</title> <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(‘password‘).value; //第一步:创建xhr对象 var xhr = null; if(window.XMLHttpRequest){//标准浏览器 xhr = new XMLHttpRequest(); }else{//早期的IE浏览器 xhr = new ActiveXObject(‘Microsoft.XMLHTTP‘); } //第二步:准备发送请求-配置发送请求的一些行为 var url = ‘02form.php?username=‘+username+‘&password=‘+password; xhr.open(‘get‘,url);
//第三步:执行发送的动作 xhr.send(null); //第四步:指定一些回调函数 xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ var data = xhr.responseText;//回调过来的值 console.log(data); } } } } } </script> </head> <body> <div> <div id="showInfo"></div> <form> 用户名:<input type="text" name="username" id="username"><br> 密码:<input type="password" name="password" id="password"><br> <input type="button" value="提交" id="btn"> </form> </div> </body> </html>
02form.php 页面
<?php header("Content-Type:text/html;charset=utf-8"); $username = $_GET[‘username‘]; $password = $_GET[‘password‘]; echo ‘用户名:‘.$username.‘密码:‘.$password."中文"; echo ‘hello world‘; ?>
在页面用户输入小明,密码输入pass
控制台结果: 用户名:小明密码:pass中文hello world
这样我们就客户端传递值到服务器端,服务器端并且可以返回值到客户端。
下面介绍一下post方法
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>原生ajax-状态值得含义</title> <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(‘password‘).value; //第一步:创建xhr对象 var xhr = null; if(window.XMLHttpRequest){//标准浏览器 xhr = new XMLHttpRequest(); }else{//早期的IE浏览器 xhr = new ActiveXObject(‘Microsoft.XMLHTTP‘); } //第二步:准备发送请求-配置发送请求的一些行为 // var url = ‘02form.php?username=‘+ username+‘&password=‘+password;//get方法 var url = ‘02form.php‘;//post方法 xhr.open(‘post‘,url,true);// xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");//post 发送字符内容 //第三步:执行发送的动作 var param = ‘username=‘+username+‘&password=‘+password;//post方法xhr.send(param); xhr.send(param); //第四步:指定一些回调函数 xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ var data = xhr.responseText;//json console.log(data); } } } } } </script> </head> <body> <div> <div id="showInfo"></div> <form> 用户名:<input type="text" name="username" id="username"><br> 密码:<input type="password" name="password" id="password"><br> <input type="button" value="提交" id="btn"> </form> </div> </body> </html>
<?php $username = $_POST[‘username‘]; $password = $_POST[‘password‘]; echo ‘用户名:‘.$username.‘密码:‘.$password."中文"; echo ‘hello world‘; ?>
原文:https://www.cnblogs.com/shangrao/p/12861845.html