javascipt之ajax Get与Post代码封装

版权声明:本文为原创文章,部分内容可能来源网络,如有侵权请联系博主,未经博主允许不得转载。 https://blog.csdn.net/qq_16546829/article/details/82803249

原生JavaScript对Ajax中的Get和Post进行封装

  • 原生的Ajax封装
  • xml格式的php发送和js处理
  • json格式的php发送和js处理

已经封装的Ajax:myAjax2.js 

调用格式和JQ的ajax类似

/*调用格式*/ 
ajax({
         type:"get",
         url:"12-ajax-json.php",
         data:{
              "a":"lnj",
              "b":"1236"
         },
         timeout: 3000,
         success: function (xhr) {
              console.log(xhr.responseText);
         /*在低版本的IE中, 不可以使用原生的JSON.parse方法,
         但是可以使用json2.js这个框架来兼容*/
         },
         error: function (xhr) {
              console.log(xhr.status);
         }
     })
function obj2str(data) {
    /*{将读入的json数据进行格式化
        "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.将对象转换为字符串+
    console.log(option);
    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{//post请求
        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) {

        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);
    }
}
<?php

//echo file_get_contents("12-ajax-json.txt"); 
echo $_GET["a"];
echo "<br>";
echo $_GET["b"];

//在ajax利用post时启用下面post进行接收反馈
/*echo $_POST["a"];
echo "<br>";
echo $_POST["b"];*/

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>12-ajax-json</title>
    <script src="myAjax2.js"></script>
    <script>
        window.onload = function (ev) {
            var oBtn = document.querySelector("button");
            oBtn.onclick = function (ev1) {
                ajax({
                    type:"get",
                    url:"12-ajax-json.php",
                    data:{
                        "a":"lnj",
                        "b":"1236"
                    },
                    timeout: 3000,
                    success: function (xhr) {
                         console.log(xhr.responseText);
     /*在低版本的IE中, 不可以使用原生的JSON.parse方法, 但是可以使用json2.js这个框架来兼容*/
                    },
                    error: function (xhr) {
                        console.log(xhr.status);
                    }
                })
            }
        }
    </script>
</head>
<body>
 <button>发送请求</button>
</body>
</html>

xml格式的php发送和js处理

服务器

// 如果PHP中需要返回XML数据, 也必须在PHP文件顶部设置
header("content-type:text/xml; charset=utf-8");

echo file_get_contents("info.xml");

ajax中success: function (xhr) {

 var res = xhr.responseXML;
console.log(res.querySelector("name").innerHTML);
console.log(res.querySelector("age").innerHTML);

Json格式的php发送和js处理

服务器

echo file_get_contents("12-ajax-json.txt"); 

ajax中success: function (xhr) {

var str = xhr.responseText;
     /*在低版本的IE中, 不可以使用原生的JSON.parse方法, 但是可以使用json2.js这个框架来兼容*/
var obj = JSON.parse(str);
//非标准字符串转换 var obj = eval("("+str+")");
// console.log(obj);
console.log(obj.name);
console.log(obj.age);

猜你喜欢

转载自blog.csdn.net/qq_16546829/article/details/82803249