Ajax——14——XML練習

一:a.php

<?php
//注意:執行結果中有中文,必須在php文件頂部設置
//header("content-type:text/html;charset=utf-8");
//如果PHP中需要返回XML數據,前端要接收到數據,必須在PHP文件頂部設置
header("content-type:text/xml;charset=utf-8");
 //在php中獲取本地的xml
echo file_get_contents("info.xml");//把要獲取文件的路徑通過參數的形式傳遞

二:b.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</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="d.js"></script>
    <!-- 括號裏的ev,ev1,是event事件對象,所有的鼠標移動,鍵盤點擊的詳細狀況都保存在這個形參裏面-->
    <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");
            oBtns[0].onclick=function(){
                var self=this;
                //調用自己封裝的js
               Ajax({
                   type:"get",
                   url:"a.php",
                   data:{"name":this.getAttribute("name")},
                   timeout: 3000,
                   success:function(xhr){
                       // console.log(xhr.responseXML);//document(全局對象),xml基本結構的代碼,和js的document類型一樣
                      var name=self.getAttribute("name");//對應第12行的self
                       var res=xhr.responseXML;
                       var title=res.querySelector(name+">title").innerHTML;//拿到以name命名的字符串爲父元素的title
                       var des=res.querySelector(name+">des").innerHTML;
                       var image=res.querySelector(name+">image").innerHTML;
                       // console.log(title);
                       // console.log(des);
                       // console.log(image);
                       oTitle.innerHTML=title;
                       oDes.innerHTML=des;
                       oImg.setAttribute("src",image);
                   },
                   error:function(xhr){
                       console.log(xhr.status);
                   }
               })
            }

        }

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


三:d.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);
    }
}

四:info.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/1=2.jpg</image>
    </bb>
    <tx>
        <title>鍵盤拖鞋</title>
        <des>程序員專屬拖鞋</des>
        <image>images/3.jpg</image>
    </tx>
</products>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章