码迷,mamicode.com
首页 > Web开发 > 详细

ajax框架封装

时间:2016-02-12 17:27:46      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:

public.js

//1、定义自调用匿名函数,用于解决函数冲突问题
(function(){
    //2、定义一个函数用于获取指定id的dom对象
    var $ = function(id){
        return document.getElementById(id);
    };
    
    //4、解决Ajax对象兼容性问题
    $.init = function() {
        //W3C浏览器
        try {
            return new XMLHttpRequest();
        } catch(e) {}
        //IE浏览器
        try {
            return new ActiveXObject(‘Microsoft.XMLHTTP‘);
        } catch(e) {}
        alert(‘您的浏览器不支持Ajax,请更换‘);
    }
    
    //5、封装Ajax中的GET请求
    $.get = function(url,data,callback,type) {
        //① 创建Ajax对象
        var xhr = $.init();
        //② 设置回调函数
        xhr.onreadystatechange = function() {
            //⑥ 判断与执行
            if(xhr.readyState==4 && xhr.status==200) {
                //判断type类型
                if(type==null) {
                    callback(xhr.responseText);
                }
                if(type==‘text‘) {
                    callback(xhr.responseText);
                }
                if(type==‘xml‘) {
                    callback(xhr.responseXML);
                }
                if(type==‘json‘) {
                    callback(eval(‘(‘+xhr.responseText+‘)‘));
                }
            }    
        }
        if(data!=null) {
            url = url+‘?‘+data;
        }
        //③ 初始化Ajax对象
        xhr.open(‘get‘,url);
        //④ 解决缓存问题
        xhr.setRequestHeader(‘If-Modified-Since‘,‘0‘);
        //⑤ 发送Ajax请求
        xhr.send(null);
    }
    
    //6、实现对Ajax中的POST请求进行封装
    $.post = function(url,data,callback,type) {
        //① 创建Ajax对象
        var xhr = $.init();
        //② 设置回调函数
        xhr.onreadystatechange = function() {
            //⑥ 判断与执行
            if(xhr.readyState==4 && xhr.status==200) {
                //判断type类型
                if(type==null) {
                    callback(xhr.responseText);
                }
                if(type==‘text‘) {
                    callback(xhr.responseText);
                }
                if(type==‘xml‘) {
                    callback(xhr.responseXML);
                }
                if(type==‘json‘) {
                    callback(eval(‘(‘+xhr.responseText+‘)‘));
                }
            }
        }
        //③ 初始化Ajax对象
        xhr.open(‘post‘,url);
        //④ 设置请求头信息
        xhr.setRequestHeader(‘Content-type‘,‘application/x-www-form-urlencoded‘);
        //⑤ 发送Ajax请求
        xhr.send(data);
    }
    
    //3、把$声明为全局变量
    window.$ = $;
})();

 

demo04.html

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script src=‘public.js‘></script>
<script>
    window.onload = function() {
        $(btnget).onclick = function() {
            //实现Ajax的get请求
            $.get(demo04_1.php,username=zhangsan,function(msg) {
                alert(msg);
            },text);
        }
        $(btnpost).onclick = function() {
            //实现Ajax的post请求
            $.post(demo04_2.php,first=100&second=20,function(msg) {
                alert(msg);
            },text);
        }
        $(btnxml).onclick = function() {
            //发送get请求获取两个数的四则运算
            $.get(demo04_3.php,first=100&second=20,function(msg){
                var jia = msg.getElementsByTagName(jia)[0].childNodes[0].nodeValue;
                var jian = msg.getElementsByTagName(jian)[0].childNodes[0].nodeValue;
                var cheng = msg.getElementsByTagName(cheng)[0].childNodes[0].nodeValue;
                var chu = msg.getElementsByTagName(chu)[0].childNodes[0].nodeValue;
                alert(jia+-+jian+-+cheng+-+chu);
            },xml);
        }
        $(btnjson).onclick = function() {
            $.post(demo04_4.php,null,function(msg){
                //清空下拉选框
                $(category).length = 0;
                for(var i=0;i<msg.length;i++) {
                    //创建op对象
                    var op = new Option(msg[i].c_name,msg[i].c_id);
                    //追加op对象到系统的category下拉选框中
                    $(category).options.add(op);
                }
            },json);
        }
    }
</script>
</head>
<body>
<input type="button" id=‘btnget‘ value=‘get请求‘ />
<input type="button" id=‘btnpost‘ value=‘post请求‘ />
<input type="button" id=‘btnxml‘ value=‘xml数据‘ />
<input type="button" id=‘btnjson‘ value=‘json数据‘ />
    <hr />
    <select id=‘category‘></select>
</body>
</html>

demo04_1.php

<?php
$username = $_GET[‘username‘];
echo ‘hello,‘.$username;

demo04_2.php

<?php
$first = $_POST[‘first‘];
$second = $_POST[‘second‘];
echo $first+$second;

demo04_3.php  --  返回XML对象

<?php
$first = $_GET[‘first‘];
$second = $_GET[‘second‘];

$jia = $first+$second;
$jian = $first-$second;
$cheng = $first*$second;
$chu = $first/$second;

$str = <<<str
    <counter>
        <jia>$jia</jia>
        <jian>$jian</jian>        
        <cheng>$cheng</cheng>        
        <chu>$chu</chu>        
    </counter>
str;
header(‘Content-type:text/xml; charset=utf-8‘);
echo $str;

demo04_4.php  --  返回JSON对象

<?php
//链接数据库
mysql_connect(‘localhost‘,‘root‘,‘mysql‘);
mysql_query(‘use Shop‘);
mysql_query(‘set names utf8‘);

//组装sql语句
$sql = "select c_id,c_name from sh_category order by c_id desc";
$res = mysql_query($sql);
$data = array();
while($row = mysql_fetch_assoc($res)) {
    $data[] = $row;
}

echo json_encode($data);

 

ajax框架封装

标签:

原文地址:http://www.cnblogs.com/bybelief/p/5187132.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!