Ajax Simple and Easy to Understand Notes

Keywords: PHP JQuery Ajax

1. get and post requests

  1. You can specify the type of send request through the method property of the form tag

  2. If it is a get request, the submitted data will be stitched behind the ** URL **

    ?userName=lnj&userPwd=123456
    
  3. If a post request places the submitted data in the ** request header **

  4. Similarities and differences between GET requests and POST requests

    1. Same:
      All submit data to remote servers
    2. Difference:
      1. Submitting data stores in different locations
        GET requests put data behind URL s
        POST requests place data in the request header
      2. Submit data size limits differ
        GET requests have size limitations on data
        POST requests do not have size limits on data
  5. GET/POST Request Application Scenario
    GET requests are used to submit non-sensitive and small data
    POST requests are used to submit sensitive and large data

<!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="Submit"><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

Be careful:
1. Uploaded files are usually submitted using POST
2. Entype="multipart/form-data" must be set for uploading files

3. Uploaded files can be accessed in PHP via $_FILES Get
4. Files in PHP are uploaded to a temporary directory by default and deleted automatically after receiving

By default, the server has a limit on the size of the uploaded file. If you want to modify the limit on the uploaded file, you can modify the php.ini file.

file_uploads = On   ;               Allow file upload On/Off Default is On
upload_max_filesize = 2048M       ; Maximum limit for uploading files
post_max_size = 2048M             ; adopt Post Most Data Submitted

max_execution_time = 30000      ; The maximum execution time for a script is in seconds
max_input_time = 30000          ; The time limit for receiving submitted data is in seconds
memory_limit = 2048M            ; Maximum memory consumption
<!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="upload"><br>
</form>
</body>
</html>

post-file.php

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

// 1. Get the dictionary for the uploaded file
$fileInfo = $_FILES["upFile"];
//print_r($fileInfo);
// 2. Get the name of the uploaded file
$fileName = $fileInfo["name"];
// 3. Get the temporary path to save the uploaded file
$filePath = $fileInfo["tmp_name"];

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

// 4. Move files
move_uploaded_file($filePath, "./source/".$fileName);
?>

2. What is Ajax

AJAX is the art of exchanging data with a server and updating parts of a Web page without reloading the entire page.

<!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. Create an asynchronous object
                var xmlhttp=new XMLHttpRequest();
                // 2. Set request mode and request address
                /*
                method: The type of request;GET or POST
                url: The location of the file on the server
                async: true(Asynchronous) or false (synchronous)
                */
                xmlhttp.open("GET", "04-ajax-get.php", true);
                // 3. Send Request
                xmlhttp.send();
                // 4. Changes in monitoring status
                xmlhttp.onreadystatechange = function (ev2) {
                    /*
                    0: Request not initialized
                    1: Server connection established
                    2: Request received
                    3: Request processing in progress
                    4: Request completed and response ready
                    */
                    if(xmlhttp.readyState === 4){
                        // Determine if the request was successful
                        if(xmlhttp.status >= 200 && xmlhttp.status < 300 ||
                           xmlhttp.status === 304){
                            // 5. Processing the returned results
                            console.log("Receive data returned by the server");
                        }else{
                            console.log("No data returned by the server was received");
                        }

                    }
                }
            }
        }
    </script>
</head>
<body>
<button>Send Request</button>
</body>
</html>

ajax-get.php

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

Request the contents of the txt file with Ajax

<!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();
                /*
                In the IE browser, if a GET request is sent through Ajax, the IE browser thinks
                Only one result for the same 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("request succeeded");
                            alert(xhr.responseText);
                        }else{
                            alert("request was aborted");
                        }
                    }
                }
            }
        }
    </script>
</head>
<body>
<button>Send Request</button>
</body>
</html>

ajax-get.txt

abc def

3. Packaging Ajax

Encapsulate Ajax and call it directly

<!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=Zhang San");
            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("request was aborted");
                });
            }
        }
    </script>

</head>
<body>
<button>Send Request</button>
</body>
</html>

myAjax.js

function obj2str(obj) {
    /*
    {
        "userName":"lnj",
        "userPwd":"123456",
        "t":"3712i9471329876498132"
    }
    */
    obj = obj || {}; // If no arguments are passed, you must create an object yourself in order to add a random factor
    obj.t = new Date().getTime();
    var res = [];
    for(var key in obj){
        // Chinese is not allowed to appear in the URL. If Chinese appears, transcoding is required.
        // The encodeURIComponent method can be called
        // Only letters/numbers/underscores/ASCII codes can appear in URL s
        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. Convert object to string
    var str = obj2str(obj); // key=value&key=value;
    // 1. Create an asynchronous object
    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. Set request mode and request address
    /*
    method: The type of request;GET or POST
    url: The location of the file on the server
    async: true(Asynchronous) or false (synchronous)
    */
    xmlhttp.open("GET", url+"?"+str, true);
    // 3. Send Request
    xmlhttp.send();
    // 4. Changes in monitoring status
    xmlhttp.onreadystatechange = function (ev2) {
        /*
        0: Request not initialized
        1: Server connection established
        2: Request received
        3: Request processing in progress
        4: Request completed and response ready
        */
        if(xmlhttp.readyState === 4){
            clearInterval(timer);
            // Determine if the request was successful
            if(xmlhttp.status >= 200 && xmlhttp.status < 300 ||
                xmlhttp.status === 304){
                // 5. Processing the returned results
                // console.log("Receive data returned by the server");
                success(xmlhttp);
            }else{
                // console.log("No data returned by the server");
                error(xmlhttp);
            }
        }
    }
    // Determine if timeouts are being passed in
    if(timeout){
        timer = setInterval(function () {
            console.log("Interrupt request");
            xmlhttp.abort();
            clearInterval(timer);
        }, timeout);
    }
}

4. User Registration ajax Interface Test

User_test.html

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>User registration ajax Interface Testing</title>
<link rel="stylesheet" href="style/common.css">
<script src="myAjax.js"></script>
<script>

/*   usage:	07-user.php?act=xxx&user=Username &pass=password
			act:
				add-Registered User
				login-Land
	
	return:	{error: 0, desc: Text Description Information}
			error:
				0	Success
				1	Failure - specific reason refer to desc
*/
window.onload = function(){ 
	var oUser = document.getElementById("add_user");
	var oPass = document.getElementById("add_pass");
	var oBtn  = document.getElementById("add_btn");

	//register
	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("fail");
        });
	};
};
</script>
</head>

<body>
<!--Land-->
<div class="loginBox">
	<ul class="loginList clearfix">
    	<li class="hTxt">User registration</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">View registered users</a></li>
    </ul>
</div>
</body>
</html>

user.php

<?php
/*
**********************************************
	usage:	07-user.php?act=xxx&user=Username &pass=password
			act:
				add-Registered User
				login-Land
	
	return:	{error: 0, desc: Text Description Information}
			error:
				0	Success
				1	Failure - specific reason refer to desc
**********************************************
*/

//Create a database and so on
$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);

//Official Start
//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: "This username has been occupied"}';
			exit();
		}
		
		$sql="INSERT INTO user (ID,username,password) VALUES(0,'{$user}','{$pass}')";
		mysql_query($sql);
		
		echo '{error: 0, desc: "login was successful"}';
		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: "Landing Success"}';
			exit();
		}
		else
		{
			echo '{error: 1, desc: "Error in username or password"}';
			exit();
		}
		break;
}
?>

user_view.php

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>User registration ajax Interface Testing</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);
//Create a database and so on
$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
//Get all users
$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>User name</td>
            <td>Password</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;*/
}
/*Land*/
.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;
}

5. 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);
                // Note: The following code must be placed between open and 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("Request succeeded ";
                            alert(xhr.responseText);
                        }else{
                            alert("Request failed ";
                        }
                    }
                }
                */

                ajax("POST", "08-ajax-post.php",{
                    "userName":"lnj",
                    "userPwd":"321"
                }, 3000, function (xhr) {
                    alert(xhr.responseText);
                }, function (xhr) {
                    alert("request was aborted");
                });
            }
        }
    </script>
</head>
<body>
<button>Send Request</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 || {}; // If no arguments are passed, you must create an object yourself in order to add a random factor
    data.t = new Date().getTime();
    var res = [];
    for(var key in data){
        // Chinese is not allowed to appear in the URL. If Chinese appears, transcoding is required.
        // The encodeURIComponent method can be called
        // Only letters/numbers/underscores/ASCII codes can appear in URL s
        res.push(encodeURIComponent(key)+"="+encodeURIComponent(data[key])); // [userName=lnj, userPwd=123456];
    }
    return res.join("&"); // userName=lnj&userPwd=123456
}
function ajax(option) {
    // 0. Convert object to string
    var str = obj2str(option.data); // key=value&key=value;
    // 1. Create an asynchronous object
    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. Set request mode and request address
    /*
    method: The type of request;GET or POST
    url: The location of the file on the server
    async: true(Asynchronous) or false (synchronous)
    */
    if(option.type.toLowerCase() === "get"){
        xmlhttp.open(option.type, option.url+"?"+str, true);
        // 3. Send Request
        xmlhttp.send();
    }else{
        xmlhttp.open(option.type, option.url,true);
        // Note: The following code must be placed between open and send
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.send(str);
    }

    // 4. Changes in monitoring status
    xmlhttp.onreadystatechange = function (ev2) {
        /*
        0: Request not initialized
        1: Server connection established
        2: Request received
        3: Request processing in progress
        4: Request completed and response ready
        */
        if(xmlhttp.readyState === 4){
            clearInterval(timer);
            // Determine if the request was successful
            if(xmlhttp.status >= 200 && xmlhttp.status < 300 ||
                xmlhttp.status === 304){
                // 5. Processing the returned results
                // console.log("Receive data returned by the server");
                option.success(xmlhttp);
            }else{
                // console.log("No data returned by the server");
                option.error(xmlhttp);
            }
        }
    }
    // Determine if timeouts are being passed in
    if(option.timeout){
        timer = setInterval(function () {
            console.log("Interrupt request");
            xmlhttp.abort();
            clearInterval(timer);
        }, option.timeout);
    }
}

6. 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("request was aborted");
                    }
                });
            }
        }
    </script>
</head>
<body>
<button>Send Request</button>
</body>
</html>

ajax-jquery.php

<?php
echo $_GET["userName"];
echo $_GET["userPwd"];
?>

Exercise: Change content with one click

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. Get the elements you need to set
            var oTitle = document.querySelector("#title");
            var oDes = document.querySelector("#des");
            var oImg = document.querySelector("img");
            // 2. Get all the buttons
            var oBtns = document.querySelectorAll("button");
            // 3. Add a click event to the button
            oBtns[0].onclick = function () {
                var self = this;
                // 4. Send Aajx requests to the server
                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">Commodity Title Name</p>
    <img src="" alt="">
    <p id="des">Commodity Description Information</p>
    <button name="nz">Dresses</button>
    <button name="bb">Package</button>
    <button name="tx">Slipper</button>
</div>
</body>
</html>

ajax-test.php

<?php
/*
// 1.Define a dictionary to store merchandise information
$products = array("nz"=>array("title"=>"Sweet Beauty dress, ""des"=>" people love, flowers, sweet series ","image"=>" images/1.jpg"),
    "bb"=>array("title"=>"Luxury donkey bag ","des "=>" for girlfriend, lover, schoolgirl, a quasi-series ","image "=>" images/2.jpg"),
    "tx"=>array("title"=>"Keyboard slippers ","des "=>" programmer's exclusive slippers, full of silk, you deserve ","image "=>" images/3.jpg");
// 2.Get parameters passed by the front end
$name = $_GET["name"];
//echo $name;
// 3.Get the corresponding dictionary based on the key passed in from the front end
$product = $products[$name];
//print_r($product);
// 4.Remove the contents of the small dictionary to the front end
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":"Sweet|Dresses",
        "des":"Everybody loves,Interflowering,Sweet Series",
        "image":"images/1.jpg"
    },
    "bb":{
        "title":"Luxury donkey bag",
        "des":"Girlfriend,Valentine,Sending to school sister,Send a Quasi Series",
        "image":"images/2.jpg"
    },
    "tx":{
        "title":"Keyboard slippers",
        "des":"Programmer's Slippers, Rich silk flavor, You deserve it",
        "image":"images/3.jpg"
    }
}

ajax-test.xml

<?xml version="1.0" encoding="UTF-8" ?>
<products>
    <nz>
        <title>Sweet|Dresses</title>
        <des>Everybody loves,Interflowering,Sweet Series</des>
        <image>images/1.jpg</image>
    </nz>
    <bb>
        <title>Luxury donkey bag</title>
        <des>Girlfriend,Valentine,Sending to school sister,Send a Quasi Series</des>
        <image>images/2.jpg</image>
    </bb>
    <tx>
        <title>Keyboard slippers</title>
        <des>Programmer's Slippers, Rich silk flavor, You deserve it</des>
        <image>images/3.jpg</image>
    </tx>
</products>

7. 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>Send Request</button>
</body>
</html>

ajax-xml.php

<?php

//Note: Chinese is included in the execution result and must be set at the top of the php file
//header("content-type:text/html; charset=utf-8");
//If you need to return XML data in PHP, you must also set it at the top of the PHP file
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>Leave</name>
    <age>21</age>
</person>

8. 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 converts json strings into objects
                    /*
                    Native JSON.parse methods are not available in lower versions of IE, but the framework json2.js can be used for compatibility
                     */
                    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>Send Request</button>
</body>
</html>

ajax-json.php

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

ajax-json.txt

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

9. Cookies

It's just a simple understanding, not a deep one

cookie: session tracking technology client
session:Session Tracking Technology Server

cookie action:
Save data from Web pages in browsers

Cook life cycle:
By default, the life cycle is a session (the browser is closed)
If expires = is set and the expiration time does not expire, the next time you open the browser it will still exist
If expires = is set and the expiration time has expired, the saved data is deleted immediately

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

cookie Notes:
Cookies do not save any data by default
Cookies cannot save more than one data at a time. To save more than one data, you can only set one cookie at a time.
Cookies are limited by **size and number**
Number limit: 20-50
Size limit: around 4KB

document.cookie = "name=lnj;";
document.cookie = "age=33;";
alert(document.cookie);
document.cookie = "name=lnj;age=33;gender=male;"; 	//This item cannot generate cookie s

Cook scope:
Access from the same browser in the same path
If in the same browser, the next level of path is accessible by default
If you want the saved cookie s to be accessible to the previous directory in the same browser, you need to add a path attribute to access them.

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

For example:
Saved to www.it666.com/jQuery/Ajax/Path,
We want to go to www.it666.com/jQuery/Ajax/13-weibo/,
And www.it666.com/jQuery/Path

For example:
We saved a cookie at www.it666.com.
So we can't access it in edu.it666.com
If we want to be accessible in edu.it666.com, we need to add another **domain** attribute to make it accessible.

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

10. cookie-Encapsulation

cookie-Encapsulation.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>16-cookie-encapsulation</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. Processing default saved paths
                // 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. Processing default saved domain s
                domain = domain || document.domain;
                // 3. Handle default expiration time
                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"));

            // By default, only cookies saved in the default path can be deleted. If you want to delete cookies saved in the specified path, you must specify the path when deleting them.
            function delCookie(key, path) {
                addCookie(key, getCookie(key), -1, path);
            }
            delCookie("name", "/");
        }
    </script>
</head>
<body>

</body>
</html>

11. hash

hash value is similar to cookies, but more effective than cookies in saving web page data
Cookies only have one session. When the browser is closed or the web address is copied directly to share with others, the web page refreshes and cannot be located directly on the specific page shared, making the shared page difficult to find.
Hash handles this problem well by putting a specific hash value at the end of a network address that can be shared with other users

<!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>

Good Ajax goes here first, then you should learn a vue

Posted by steveness on Sat, 04 Sep 2021 23:38:55 -0700