解決瀏覽器兼容性問題
if (window.XMLHttpRequest){
//? IE7+, Firefox, Chrome, Opera, Safari 瀏覽器執(zhí)行代碼
xmlhttp=new XMLHttpRequest();}
else{
// IE6, IE5 瀏覽器執(zhí)行代碼
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}
AJAX獲取PHP后臺數(shù)據(jù)------------登錄判斷----get
第一步:獲取對象晤愧;
var btn = document.getElementById("login-btn");
第二步:為對象添加click點擊事件
btn.addEventListener("click",function () {}
第三步:創(chuàng)建創(chuàng)建xhr(XMLHttpRequest())對象驴一,并且獲取對應的值
var xhr =new XMLHttpRequest();
var username = document.getElementById("username-ipt").value;
var password = document.getElementById("password-ipt").value;
//獲取表單value,并拼接成字符
var getInf ="username=" + username +"&password=" + password;
第四步:打開AJAX的異步連接
//將getInf字符帶入PHP后臺;
xhr.open("GET","http://localhost:63342/phpone/EnterPHP.php?"+getInf);//GET請求
//第五步:發(fā)送異步請求
xhr.send();
//判斷傳輸是否成功并且進行前端操作
xhr.onreadystatechange =function () {
if(xhr.readyState ==4 && xhr.status ==200){
document.getElementById("result").innerText = xhr.responseText;}}
------------enter.html------get
AJAX獲取PHP后臺數(shù)據(jù)------------登錄判斷----POST
將open打開異步連接中的method方法改為POST,
open中去掉getInf的拼接赋元,改用在發(fā)送異步請求中拼接,xhr.send(getInf);同時還要在send前加一句
//xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
------------enter.html-----post
------------EnterPHP.php
//兼容get與post使用方法
$username = $_POST["username"];
if($username == "" || $username == null){
? ? $username = $_GET["username"];
}
$password? = $_POST["password"];
if($password? == "" || $password? == null){
? ? $password? = $_GET["password"];
}