ajax

2018-08-15  本文已影响0人  Wonder茂茂

解决浏览器兼容性问题

if (window.XMLHttpRequest){

//  IE7+, Firefox, Chrome, Opera, Safari 浏览器执行代码

xmlhttp=new XMLHttpRequest();}

else{

// IE6, IE5 浏览器执行代码

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");}


AJAX获取PHP后台数据------------登录判断----get

第一步:获取对象;

var btn = document.getElementById("login-btn");

第二步:为对象添加click点击事件

btn.addEventListener("click",function () {}

第三步:创建创建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请求

//第五步:发送异步请求

xhr.send();

//判断传输是否成功并且进行前端操作

xhr.onreadystatechange =function () {

if(xhr.readyState ==4 && xhr.status ==200){

document.getElementById("result").innerText = xhr.responseText;}}

------------enter.html------get


AJAX获取PHP后台数据------------登录判断----POST

将open打开异步连接中的method方法改为POST,

open中去掉getInf的拼接,改用在发送异步请求中拼接,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"];

}


上一篇 下一篇

猜你喜欢

热点阅读