Ajax简单易理解笔记

一、get和post请求

  1. 可以通过form标签的method属性指定发送请求的类型

  2. 如果是get请求会将提交的数据拼接到**URL后面**

    ?userName=lnj&userPwd=123456
    
  3. 如果是post请求会将提交的数据放到**请求头中**

  4. GET请求和POST请求的异同

    1. 相同点:
      都是将数据提交到远程服务器
    2. 不同点:
      1. 提交数据存储的位置不同
        GET请求会将数据放到URL后面
        POST请求会将数据放到请求头中
      2. 提交数据大小限制不同
        GET请求对数据有大小限制
        POST请求对数据没有大小限制
  5. GET/POST请求应用场景
    GET请求用于提交非敏感数据和小数据
    POST请求用于提交敏感数据和大数据

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>02-get</title>
</head>
<body>

<form action="02-get-post.php" method="post">
    <input type="text" name="userName"><br>
    <input type="password" name="userPwd"><br>
    <input type="submit" value="提交"><br>
</form>
</body>
</html>

get-post.php

<?php
print_r($_GET);
echo $_GET["userName"];
echo $_GET["userPwd"];

print_r($_POST);
echo $_POST["userName"];
echo $_POST["userPwd"];
?>
1.post-file

注意:
1.上传文件一般使用POST提交
2.上传文件必须设置enctype=“multipart/form-data”

3.上传的文件在PHP中可以通过$_FILES获取
4.PHP中文件默认会上传到一个临时目录, 接收完毕之后会自动删除

默认情况下服务器对上传文件的大小是有限制的, 如果想修改上传文件的限制可以修改php.ini文件

file_uploads = On   ;               是否允许上传文件 On/Off 默认是On
upload_max_filesize = 2048M       ; 上传文件的最大限制
post_max_size = 2048M             ; 通过Post提交的最多数据

max_execution_time = 30000      ; 脚本最长的执行时间 单位为秒
max_input_time = 30000          ; 接收提交的数据的时间限制 单位为秒
memory_limit = 2048M            ; 最大的内存消耗
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>03-post-file</title>
</head>
<body>

<form action="post-file.php" method="post" enctype="multipart/form-data">
    <input type="file" name="upFile"><br>
    <input type="submit" value="上传"><br>
</form>
</body>
</html>

post-file.php

<?php
//echo "post page";
//print_r($_POST);
//echo "<br>";
//print_r($_FILES);

// 1.获取上传文件对应的字典
$fileInfo = $_FILES["upFile"];
//print_r($fileInfo);
// 2.获取上传文件的名称
$fileName = $fileInfo["name"];
// 3.获取上传文件保存的临时路径
$filePath = $fileInfo["tmp_name"];

//echo $fileName;
//echo "<br>";
//echo $filePath;

// 4.移动文件
move_uploaded_file($filePath, "./source/".$fileName);
?>

二、什么是Ajax

AJAX 是与服务器交换数据并更新部分网页的艺术,在不重新加载整个页面的情况下。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>04-ajax-get</title>
 
    <script>
        window.onload = function (ev) {
            var oBtn = document.querySelector("button");
            oBtn.onclick = function (ev1) {
                // 1.创建一个异步对象
                var xmlhttp=new XMLHttpRequest();
                // 2.设置请求方式和请求地址
                /*
                method:请求的类型;GET 或 POST
                url:文件在服务器上的位置
                async:true(异步)或 false(同步)
                */
                xmlhttp.open("GET", "04-ajax-get.php", true);
                // 3.发送请求
                xmlhttp.send();
                // 4.监听状态的变化
                xmlhttp.onreadystatechange = function (ev2) {
                    /*
                    0: 请求未初始化
                    1: 服务器连接已建立
                    2: 请求已接收
                    3: 请求处理中
                    4: 请求已完成,且响应已就绪
                    */
                    if(xmlhttp.readyState === 4){
                        // 判断是否请求成功
                        if(xmlhttp.status >= 200 && xmlhttp.status < 300 ||
                           xmlhttp.status === 304){
                            // 5.处理返回的结果
                            console.log("接收到服务器返回的数据");
                        }else{
                            console.log("没有接收到服务器返回的数据");
                        }

                    }
                }
            }
        }
    </script>
</head>
<body>
<button>发送请求</button>
</body>
</html>

ajax-get.php

<?php
//sleep(5);
//echo "ajax get page";
echo $_GET["userName"];
echo "<br>";
echo $_GET["userPwd"];
?>

用Ajax请求txt文件的内容

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>05-ajax-get</title>

    <script>
        window.onload = function (ev) {

            var oBtn = document.querySelector("button");
            oBtn.onclick = function (ev1) {
                var xhr;
                if (window.XMLHttpRequest)
                {// code for IE7+, Firefox, Chrome, Opera, Safari
                    xhr=new XMLHttpRequest();
                }
                else
                {// code for IE6, IE5
                    xhr=new ActiveXObject("Microsoft.XMLHTTP");
                }
                // var xhr = new XMLHttpRequest();
                /*
                在IE浏览器中, 如果通过Ajax发送GET请求, 那么IE浏览器认为
                同一个URL只有一个结果
                05-ajax-get.txt === abc

                console.log(Math.random());
                console.log(new Date().getTime());
                */
                xhr.open("GET","05-ajax-get.txt?t="+(new Date().getTime()),true);
                xhr.send();
                xhr.onreadystatechange = function (ev2) {
                    if(xhr.readyState === 4){
                        if(xhr.status >= 200 && xhr.status < 300 ||
                        xhr.status === 304){
                            // alert("请求成功");
                            alert(xhr.responseText);
                        }else{
                            alert("请求失败");
                        }
                    }
                }
            }
        }
    </script>
</head>
<body>
<button>发送请求</button>
</body>
</html>

ajax-get.txt

abc def

三、封装Ajax

把Ajax封装起来,就可以直接调用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>06-ajax-get</title>
    <script src="myAjax.js"></script>
    <script>
        window.onload = function (ev) {
            var oBtn = document.querySelector("button");
            var res = encodeURIComponent("wd=张三");
            console.log(res);
            oBtn.onclick = function (ev1) {
                //                            %E5%BC%A0%E4%B8%89
                // https://www.baidu.com/s?wd=%E5%BC%A0%E4%B8%89
                // url?key=value&key=value;
                ajax("04-ajax-get.php", {
                    "userName":"lnj",
                    "userPwd":"123456"
                }, 3000
                , function (xhr) {
                    alert(xhr.responseText);
                }, function (xhr) {
                    alert("请求失败");
                });
            }
        }
    </script>

</head>
<body>
<button>发送请求</button>
</body>
</html>

myAjax.js

function obj2str(obj) {
    /*
    {
        "userName":"lnj",
        "userPwd":"123456",
        "t":"3712i9471329876498132"
    }
    */
    obj = obj || {}; // 如果没有传参, 为了添加随机因子,必须自己创建一个对象
    obj.t = new Date().getTime();
    var res = [];
    for(var key in obj){
        // 在URL中是不可以出现中文的, 如果出现了中文需要转码
        // 可以调用encodeURIComponent方法
        // URL中只可以出现字母/数字/下划线/ASCII码
        res.push(encodeURIComponent(key)+"="+encodeURIComponent(obj[key])); // [userName=lnj, userPwd=123456];
    }
    return res.join("&"); // userName=lnj&userPwd=123456
}
function ajax(url, obj, timeout, success, error) {
    // 0.将对象转换为字符串
    var str = obj2str(obj); // key=value&key=value;
    // 1.创建一个异步对象
    var xmlhttp, timer;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    // 2.设置请求方式和请求地址
    /*
    method:请求的类型;GET 或 POST
    url:文件在服务器上的位置
    async:true(异步)或 false(同步)
    */
    xmlhttp.open("GET", url+"?"+str, true);
    // 3.发送请求
    xmlhttp.send();
    // 4.监听状态的变化
    xmlhttp.onreadystatechange = function (ev2) {
        /*
        0: 请求未初始化
        1: 服务器连接已建立
        2: 请求已接收
        3: 请求处理中
        4: 请求已完成,且响应已就绪
        */
        if(xmlhttp.readyState === 4){
            clearInterval(timer);
            // 判断是否请求成功
            if(xmlhttp.status >= 200 && xmlhttp.status < 300 ||
                xmlhttp.status === 304){
                // 5.处理返回的结果
                // console.log("接收到服务器返回的数据");
                success(xmlhttp);
            }else{
                // console.log("没有接收到服务器返回的数据");
                error(xmlhttp);
            }
        }
    }
    // 判断外界是否传入了超时时间
    if(timeout){
        timer = setInterval(function () {
            console.log("中断请求");
            xmlhttp.abort();
            clearInterval(timer);
        }, timeout);
    }
}

四、用户注册ajax接口测试

User_test.html

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>用户注册ajax接口测试</title>
<link rel="stylesheet" href="style/common.css">
<script src="myAjax.js"></script>
<script>

/*   usage:	07-user.php?act=xxx&user=用户名&pass=密码
			act:
				add——注册用户
				login——登陆
	
	return:	{error: 0, desc: 文字描述信息}
			error:
				0	成功
				1	失败——具体原因参考desc
*/
window.onload = function(){ 
	var oUser = document.getElementById("add_user");
	var oPass = document.getElementById("add_pass");
	var oBtn  = document.getElementById("add_btn");

	//注册
	oBtn.onclick = function(){

	    var json = {
	        "act": "add",
            "user":oUser.value,
            "pass":oPass.value
        };
	    ajax("07-user.php",json,function (xhr) {
            alert(xhr.responseText);
        }, function (xhr) {
            alert("失败");
        });
	};
};
</script>
</head>

<body>
<!--登陆-->
<div class="loginBox">
	<ul class="loginList clearfix">
    	<li class="hTxt">用户注册</li>
        <li class="inputBox">
        	<input type="text" class="inputs" id="add_user">
        </li>
        <li class="inputBox">
        	<input type="password" class="inputs" id="add_pass">
        </li>
        <li class="btns">
            <input id="add_btn" type="button" class="reg" value="" />
        </li>
        <li class="look"><a href="07-user_view.php" target="_blank">查看已注册用户</a></li>
    </ul>
</div>
</body>
</html>

user.php

<?php
/*
**********************************************
	usage:	07-user.php?act=xxx&user=用户名&pass=密码
			act:
				add——注册用户
				login——登陆
	
	return:	{error: 0, desc: 文字描述信息}
			error:
				0	成功
				1	失败——具体原因参考desc
**********************************************
*/

//创建数据库之类的
$db=@mysql_connect('localhost', 'root', '') or @mysql_connect('localhost', 'root', 'admin');

mysql_query("set names 'utf8'");
mysql_query('CREATE DATABASE it666_ajax');

mysql_select_db('it666_ajax');

$sql= <<< END
CREATE TABLE  `it666_ajax`.`user` (
`ID` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`username` VARCHAR( 255 ) NOT NULL ,
`password` VARCHAR( 255 ) NOT NULL
) CHARACTER SET utf8 COLLATE utf8_general_ci
END;

mysql_query($sql);

//正式开始
//header('Content-type:zns/json');

$act=$_GET['act'];
$user=strtolower($_GET['user']);
$pass=$_GET['pass'];

switch($act)
{
	case 'add':
		$sql="SELECT COUNT(*) FROM user WHERE username='{$user}'";
		
		$res=mysql_query($sql);
		
		$row=mysql_fetch_array($res);
		
		if((int)$row[0]>0)
		{
			echo '{error: 1, desc: "此用户名已被占用"}';
			exit();
		}
		
		$sql="INSERT INTO user (ID,username,password) VALUES(0,'{$user}','{$pass}')";
		mysql_query($sql);
		
		echo '{error: 0, desc: "注册成功"}';
		break;
	case 'login':
		$sql="SELECT COUNT(*) FROM user WHERE username='{$user}' AND password='{$pass}'";
		$res=mysql_query($sql);
		
		$row=mysql_fetch_array($res);
		
		if((int)$row[0]>0)
		{
			echo '{error: 0, desc: "登陆成功"}';
			exit();
		}
		else
		{
			echo '{error: 1, desc: "用户名或密码有误"}';
			exit();
		}
		break;
}
?>

user_view.php

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>用户注册ajax接口测试</title>
<style>
*{margin:0; padding:0;}
table{border-collapse:collapse; font-family:"Microsoft YaHei"; width:500px; margin:10px auto;}
td,th{border:solid #000 1px; padding:5px 7px;}
tr:nth-child(2n){background:#EAEAEA;}
thead tr:nth-child(1){background:#CECECE;}
tr:hover{background:#D7D7D7;}
::selection {background-color:#669900; color:#ffffff;}
::-moz-selection {background-color:#669900; color:#ffffff;}
</style>
</head>

<body>
<?php
error_reporting(E_ALL ^ E_DEPRECATED);
//创建数据库之类的
$db=mysql_connect('localhost', 'root', '');

mysql_query("set names 'utf8'");
mysql_query('CREATE DATABASE it666_ajax');

mysql_select_db('it666_ajax');

$sql= <<< END
CREATE TABLE  `it666_ajax`.`user` (
`ID` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`username` VARCHAR( 255 ) NOT NULL ,
`password` VARCHAR( 255 ) NOT NULL
) CHARACTER SET utf8 COLLATE utf8_general_ci
END;

mysql_query($sql);
?>
<?php
//获取所有用户
$sql='SELECT ID, username, password FROM user ORDER BY ID DESC';

$res=mysql_query($sql);
?>
<table border="0" cellpadding="0" cellspacing="0">
	<thead>
    	<tr>
            <td>ID</td>
            <td>用户名</td>
            <td>密码</td>
        </tr>
    </thead>
    <tbody>
<?php
while($row=mysql_fetch_array($res))
{
?>
    	<tr>
        	<td><?php echo $row[0]; ?></td>
        	<td><?php echo $row[1]; ?></td>
        	<td><?php echo $row[2]; ?></td>
        </tr>
<?php
}
?>
    </tbody>
</table>
</body>
</html>

common.css

@charset "utf-8";
*{
	margin:0;
	padding:0;
}
li{
	list-style:none;
}
img{
	border:none;
}
a{
	text-decoration:none;
}
input,textarea{
	outline:none;
	resize:none;
	border:none;
}
.clearfix:after{
	visibility:hidden;
	display:block;
	font-size:0;
	content:" ";
	clear:both;
	height:0;
}
.clearfix{
	*zoom:1;
}
html,body{
	width: 100%;
	height: 100%;
}
body{
	background:url(../images/bg.jpg) center 0 no-repeat;
	/*background-size:cover;*/
}
/*登陆*/
.loginBox{
	width:278px;
	padding:30px 80px 20px 80px;
	margin:150px auto;
	background-image: linear-gradient(top,rgb(255,255,255),rgb(242,242,242));
	box-shadow: 0 0 3px rgba(21,62,78,0.8);
	position:relative;
	border-radius:2px;
}
.loginList{
	width:100%;
}
.loginList li{
	margin-bottom:10px;
	overflow:hidden;
}
.hTxt{
	font:18px/1.5 "Microsoft YaHei";
}
.inputs{
	width:260px;
	display:block;
	font-weight:bold;
	background:url(../images/inputBg.png) 0 0 no-repeat;
	height:14px;
	line-height:14px;
	padding:9px;
	color:#666;
}
.loginList .btns{
	text-align:right;
	background:none;
	width:280px;
}
.reg{
	background:url(../images/btns.png) 0 -42px no-repeat;
	width:70px;
	height:42px;
	display:inline-block;
	overflow:hidden;
	opacity:.8;
}
.login{
	background:url(../images/btns.png) 0 0 no-repeat;
	width:70px;
	height:42px;
	display:inline-block;
	overflow:hidden;
	opacity:.8;
}
.reg:hover,.login:hover{
	opacity:1;
}
.reg:active,.login:active{
	opacity:.9;
}
.look{
	text-align:right;
	font:12px/1.2 "Microsoft YaHei";
	color:#999;
}
::selection {
	background-color:#669900;
	color:#ffffff;
}
::-moz-selection {
	background-color:#669900;
	color:#ffffff;
}

五、ajax-post

ajax-post.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>08-ajax-post</title>
    <script src="myAjax2.js"></script>
    <script>
        window.onload = function (ev) {

            var oBtn = document.querySelector("button");
            oBtn.onclick = function (ev1) {
                /*
                var xhr;
                if (window.XMLHttpRequest)
                {// code for IE7+, Firefox, Chrome, Opera, Safari
                    xhr=new XMLHttpRequest();
                }
                else
                {// code for IE6, IE5
                    xhr=new ActiveXObject("Microsoft.XMLHTTP");
                }
                // var xhr = new XMLHttpRequest();
                xhr.open("POST","08-ajax-post.php",true);
                // 注意点: 以下代码必须放到open和send之间
                xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
                xhr.send("userName=zs&userPwd=321");
                xhr.onreadystatechange = function (ev2) {
                    if(xhr.readyState === 4){
                        if(xhr.status >= 200 && xhr.status < 300 ||
                        xhr.status === 304){
                            // alert("请求成功");
                            alert(xhr.responseText);
                        }else{
                            alert("请求失败");
                        }
                    }
                }
                */

                ajax("POST", "08-ajax-post.php",{
                    "userName":"lnj",
                    "userPwd":"321"
                }, 3000, function (xhr) {
                    alert(xhr.responseText);
                }, function (xhr) {
                    alert("请求失败");
                });
            }
        }
    </script>
</head>
<body>
<button>发送请求</button>
</body>
</html>

ajax-post.php

<?php
//echo "ajax post page";
echo $_POST["userName"];
echo $_POST["userPwd"];
?>

myAjax2.js

function obj2str(data) {
    /*
    {
        "userName":"lnj",
        "userPwd":"123456",
        "t":"3712i9471329876498132"
    }
    */
    data = data || {}; // 如果没有传参, 为了添加随机因子,必须自己创建一个对象
    data.t = new Date().getTime();
    var res = [];
    for(var key in data){
        // 在URL中是不可以出现中文的, 如果出现了中文需要转码
        // 可以调用encodeURIComponent方法
        // URL中只可以出现字母/数字/下划线/ASCII码
        res.push(encodeURIComponent(key)+"="+encodeURIComponent(data[key])); // [userName=lnj, userPwd=123456];
    }
    return res.join("&"); // userName=lnj&userPwd=123456
}
function ajax(option) {
    // 0.将对象转换为字符串
    var str = obj2str(option.data); // key=value&key=value;
    // 1.创建一个异步对象
    var xmlhttp, timer;
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    // 2.设置请求方式和请求地址
    /*
    method:请求的类型;GET 或 POST
    url:文件在服务器上的位置
    async:true(异步)或 false(同步)
    */
    if(option.type.toLowerCase() === "get"){
        xmlhttp.open(option.type, option.url+"?"+str, true);
        // 3.发送请求
        xmlhttp.send();
    }else{
        xmlhttp.open(option.type, option.url,true);
        // 注意点: 以下代码必须放到open和send之间
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.send(str);
    }

    // 4.监听状态的变化
    xmlhttp.onreadystatechange = function (ev2) {
        /*
        0: 请求未初始化
        1: 服务器连接已建立
        2: 请求已接收
        3: 请求处理中
        4: 请求已完成,且响应已就绪
        */
        if(xmlhttp.readyState === 4){
            clearInterval(timer);
            // 判断是否请求成功
            if(xmlhttp.status >= 200 && xmlhttp.status < 300 ||
                xmlhttp.status === 304){
                // 5.处理返回的结果
                // console.log("接收到服务器返回的数据");
                option.success(xmlhttp);
            }else{
                // console.log("没有接收到服务器返回的数据");
                option.error(xmlhttp);
            }
        }
    }
    // 判断外界是否传入了超时时间
    if(option.timeout){
        timer = setInterval(function () {
            console.log("中断请求");
            xmlhttp.abort();
            clearInterval(timer);
        }, option.timeout);
    }
}

六、ajax-jquery

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>09-ajax-jquery</title>
    <!--<script src="js/jquery-1.12.4.js"></script>-->
    <script src="myAjax2.js"></script>
    <script>
        window.onload = function (ev) {

            var oBtn = document.querySelector("button");
            oBtn.onclick = function (ev1) {
                // $.ajax({
                //     url: "09-ajax-jquery.php",
                //     type: "get",
                //     data: "userName=lnj&userPwd=654321",
                //     success: function(msg){
                //         alert(msg );
                //     },
                //     error: function (xhr) {
                //         alert(xhr.status);
                //     }
                // });

                ajax({
                    url:"ajax-get.php",
                    data:{
                        "userName":"lnj",
                        "userPwd":"123456"
                    },
                    timeout: 3000,
                    type:"post",
                    success: function (xhr) {
                        alert(xhr.responseText);
                    },
                    error: function (xhr) {
                        alert("请求失败");
                    }
                });
            }
        }
    </script>
</head>
<body>
<button>发送请求</button>
</body>
</html>

ajax-jquery.php

<?php
echo $_GET["userName"];
echo $_GET["userPwd"];
?>
练习:一键换内容

ajax-test.html

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>10-ajax-test</title>
    <style>
        *{
            margin: 0;
            padding: 0;
        }
        div{
            width: 300px;
            height: 300px;
            border: 1px solid #000;
            margin: 50px auto;
            text-align: center;
            background: #ccc;
        }
        img{
            width: 200px;
            height: 200px;
            display: block;
            margin: 10px auto 10px;
            border: 1px solid #000;
        }
        p{
            text-align: center;
            background: pink;
        }
    </style>
    <script src="myAjax2.js"></script>
    <script>
        window.onload = function (ev) {
            // 1.获取需要设置的元素
            var oTitle = document.querySelector("#title");
            var oDes = document.querySelector("#des");
            var oImg = document.querySelector("img");
            // 2.获取所有按钮
            var oBtns = document.querySelectorAll("button");
            // 3.给按钮添加点击事件
            oBtns[0].onclick = function () {
                var self = this;
                // 4.发送Aajx请求到服务器
                ajax({
                    type:"get",
                    url:"ajax-test.php",
                    data:{"name":this.getAttribute("name")},
                    timeout: 3000,
                    success: function (xhr) {
                        /*
                        // alert(xhr.responseText);
                        var res = xhr.responseText.split("|");
                        // console.log(res);
                        oTitle.innerHTML = res[0];
                        oDes.innerHTML = res[1];
                        oImg.setAttribute("src", res[2]);
                        */

                        /*
                        var name = self.getAttribute("name");
                        var res = xhr.responseXML;
                        var title = res.querySelector(name+">title").innerHTML;
                        var des = res.querySelector(name+">des").innerHTML;
                        var image = res.querySelector(name+">image").innerHTML;
                        oTitle.innerHTML = title;
                        oDes.innerHTML = des;
                        oImg.setAttribute("src", image);
                         */


                        var name = self.getAttribute("name");
                        var str = xhr.responseText;
                        var obj = JSON.parse(str);
                        // console.log(obj);
                        var subObj = obj[name];
                        // console.log(subObj);
                        oTitle.innerHTML = subObj.title;
                        oDes.innerHTML = subObj.des;
                        oImg.setAttribute("src", subObj.image);

                    },
                    error: function (xhr) {
                        alert(xhr.status);
                    }
                });
            }
            oBtns[1].onclick = function () {

            }
            oBtns[2].onclick = function () {

            }
        }
    </script>
</head>
<body>
<div>
    <p id="title">商品标题名称</p>
    <img src="" alt="">
    <p id="des">商品描述信息</p>
    <button name="nz">女装</button>
    <button name="bb">包包</button>
    <button name="tx">拖鞋</button>
</div>
</body>
</html>

ajax-test.php

<?php
/*
// 1.定义字典保存商品信息
$products = array("nz"=>array("title"=>"甜美女装", "des"=>"人见人爱,花间花开,甜美系列", "image"=>"images/1.jpg"),
    "bb"=>array("title"=>"奢华驴包", "des"=>"送女友,送情人,送学妹,一送一个准系列", "image"=>"images/2.jpg"),
    "tx"=>array("title"=>"键盘拖鞋", "des"=>"程序员专属拖鞋, 屌丝气息浓郁, 你值得拥有", "image"=>"images/3.jpg"));
// 2.获取前端传递的参数
$name = $_GET["name"];
//echo $name;
// 3.根据前端传入的key,获取对应的字典
$product = $products[$name];
//print_r($product);
// 4.将小字典中的内容取出来返回给前端
echo $product["title"];
echo "|";
echo $product["des"];
echo "|";
echo $product["image"];
*/


/*
header("content-type:text/xml; charset=utf-8");

echo file_get_contents("10-ajax-test.xml");
*/


echo file_get_contents("ajax-test.txt");

ajax-test.txt

{
    "nz":{
        "title":"甜美|女装",
        "des":"人见人爱,花间花开,甜美系列",
        "image":"images/1.jpg"
    },
    "bb":{
        "title":"奢华驴包",
        "des":"送女友,送情人,送学妹,一送一个准系列",
        "image":"images/2.jpg"
    },
    "tx":{
        "title":"键盘拖鞋",
        "des":"程序员专属拖鞋, 屌丝气息浓郁, 你值得拥有",
        "image":"images/3.jpg"
    }
}

ajax-test.xml

<?xml version="1.0" encoding="UTF-8" ?>
<products>
    <nz>
        <title>甜美|女装</title>
        <des>人见人爱,花间花开,甜美系列</des>
        <image>images/1.jpg</image>
    </nz>
    <bb>
        <title>奢华驴包</title>
        <des>送女友,送情人,送学妹,一送一个准系列</des>
        <image>images/2.jpg</image>
    </bb>
    <tx>
        <title>键盘拖鞋</title>
        <des>程序员专属拖鞋, 屌丝气息浓郁, 你值得拥有</des>
        <image>images/3.jpg</image>
    </tx>
</products>

七、ajax-xml

ajax-xml.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>11-ajax-xml</title>
    <script src="myAjax2.js"></script>
    <script>
        window.onload = function (ev) {

            var oBtn = document.querySelector("button");
            oBtn.onclick = function (ev1) {
                ajax({
                    type: "get",
                    url: "ajax-xml.php",
                    success:function (xhr){
                        // console.log(xhr.responseXML);
                        // console.log(document);
                        var res =xhr.responseXML;
                        console.log(res.querySelector("name").innerHTML);
                        console.log(res.querySelector("age").innerHTML);
                    },
                    error: function (xhr) {
                        console.log(xhr.status);
                    }
                })
            }
        }
    </script>
</head>
<body>
<button>发送请求</button>
</body>
</html>

ajax-xml.php

<?php

//注意: 执行结果中有中文, 必须在php文件顶部设置
//header("content-type:text/html; charset=utf-8");
//如果PHP中需要返回XML数据,也必须在PHP文件顶部设置
header("content-type:text/xml; charset=utf-8");
echo file_get_contents("info.xml");

info.xml

<?xml version="1.0" encoding="UTF-8" ?>
<person>
    <name>小离</name>
    <age>21</age>
</person>

八、Ajax-json

ajax-json.html

<script>
    window.onload = function (ev) {

        var oBtn = document.querySelector("button");
        oBtn.onclick = function (ev1) {
            ajax({
                type: "get",
                url: "ajax-json.php",
                success:function (xhr){
                    // console.log(xhr.responseText);
                    var str = xhr.responseText;
                    //JSON.parse可以将json字符串转换成对象
                    /*
                    在低版本的IE中,不可以使用原生的JSON.parse方法,但是可以使用json2.js这个框架来兼容
                     */
                    var obj = JSON.parse(str);
                    console.log(obj.name);
                    console.log(obj.age);
                },
                error: function (xhr) {
                    console.log(xhr.status);
                }
            })
        }
    }
</script>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>12-ajax-json</title>
    <script src="myAjax2.js"></script>
</head>
<body>
<button>发送请求</button>
</body>
</html>

ajax-json.php

<?php
echo file_get_contents("ajax-json.txt");

ajax-json.txt

{
    "name": "xioali",
    "age": "21"
}

九、cookie

这里只是简单理解一下,并没有深究

cookie: 会话跟踪技术 客户端
session: 会话跟踪技术 服务端

cookie作用:
将网页中的数据保存到浏览器中

cookie生命周期:
默认情况下生命周期是一次会话(浏览器被关闭)
如果通过expires=设置了过期时间, 并且过期时间没有过期, 那么下次打开浏览器还是存在
如果通过expires=设置了过期时间, 并且过期时间已经过期了,那么会立即删除保存的数据

alert(document.cookie);
var date = new Date();
date.setDate(date.getDate() - 1);
document.cookie = "age=33;expires="+date.toGMTString()+";";
alert(document.cookie);

cookie注意点:
cookie默认不会保存任何的数据
cookie不能一次性保存多条数据, 要想保存多条数据,只能一条一条的设置
cookie有**大小个数**的限制
个数限制: 20~50
大小限制: 4KB左右

document.cookie = "name=lnj;";
document.cookie = "age=33;";
alert(document.cookie);
document.cookie = "name=lnj;age=33;gender=male;"; 	//这一条不能生成cookie

cookie作用范围:
同一个浏览器的同一个路径下访问
如果在同一个浏览器中, 默认情况下下一级路径就可以访问
如果在同一个浏览器中, 想让上一级目录也能访问保存的cookie, 那么需要添加一个path属性才可以;

document.cookie = "name=zs;path=/;";

例如:
保存到了www.it666.com/jQuery/Ajax/ 路径下,
我们想在 www.it666.com/jQuery/Ajax/13-weibo/,
www.it666.com/jQuery/ 路径下也能访问

例如:
我们在www.it666.com 下面保存了一个cookie,
那么我们在edu.it666.com 中是无法访问的
如果想在edu.it666.com 中也能访问, 那么我们需要再添加一个**domain**属性才可以;

document.cookie = "name=zs;path=/;domain=it666.com;";

十、cookie-封装

cookie-封装.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>16-cookie-封装</title>
    <script>
        window.onload = function (ev) {
            // document.cookie = "age=88;";

            // addCookie("gender", "male");
            // addCookie("score", "998", 1, "/", "127.0.0.1");
            function addCookie(key, value, day, path, domain) {
                // 1.处理默认保存的路径
                // if(!path){
                //     var index = window.location.pathname.lastIndexOf("/")
                //     var currentPath = window.location.pathname.slice(0, index);
                //     path = currentPath;
                // }
                var index = window.location.pathname.lastIndexOf("/")
                var currentPath = window.location.pathname.slice(0, index);
                path = path || currentPath;
                // 2.处理默认保存的domain
                domain = domain || document.domain;
                // 3.处理默认的过期时间
                if(!day){
                    document.cookie = key+"="+value+";path="+path+";domain="+domain+";";
                }else{
                    var date = new Date();
                    date.setDate(date.getDate() + day);
                    document.cookie = key+"="+value+";expires="+date.toGMTString()+";path="+path+";domain="+domain+";";
                }
            }

            function getCookie(key) {
                // console.log(document.cookie);
                var res = document.cookie.split(";");
                // console.log(res);
                for(var i = 0; i < res.length; i++){
                    // console.log(res[i]);
                    var temp = res[i].split("=");
                    // console.log(temp);
                    if(temp[0].trim() === key){
                        return temp[1];
                    }
                }
            }
            console.log(getCookie("name"));

            // 默认情况下只能删除默认路径中保存的cookie, 如果想删除指定路径保存的cookie, 那么必须在删除的时候指定路径才可以
            function delCookie(key, path) {
                addCookie(key, getCookie(key), -1, path);
            }
            delCookie("name", "/");
        }
    </script>
</head>
<body>

</body>
</html>

十一、hash

hash值跟cookie差不多,但是比cookie更具有保存网页数据的效果
cookie的话只有一次会话,浏览器关闭之后或者直接复制网址分享给别人网页会刷新,不能直接定位到分享的具体页面,导致分享的页面 很难找到
hash很好的处理了这个问题,它将特定的hash值放入网络地址尾部,可以跟网址一起分享给其他用户

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>17-hash</title>
    <script>
        window.location.hash = 3;
        console.log(window.location.hash.substring(1));
    </script>
</head>
<body>

</body>
</html>

好的Ajax就先到这里,接下来应该学个vue

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值