JavaScript封装Ajax(类JQuery中$.ajax()方法)

ajax.js

(function(exports, document, undefined){
    "use strict";
    function Ajax(){
        if(!(this instanceof Ajax)) return;
        return this;
    }
    Ajax.prototype = {
        init: function(opts){
            opts = opts || {};
            this.opts = opts;
            this.opts.type = opts.type || ‘get‘;
            this.opts.url = opts.url || ‘‘;
            this.opts.data = opts.data || ‘‘;
            this.opts.dataType = opts.dataType || ‘text‘;
            this.opts.async = opts.async || true;
            this.opts.success = opts.success || null;
            this.opts.error = opts.error || null;
            this.xhr = this.createXMLHttpRequest.call(this);
            this.initEvent.call(this);
            return this;
        },
        ajax: function(opts){
            this.init.apply(this, arguments);
            this.open.call(this);
            this.send.call(this);
        },
        createXMLHttpRequest: function(){
            var xhr;
            try{
                xhr = new XMLHttpRequest();
            }catch(e){
                console.log(e);
            }
            return xhr;
        },
        initEvent: function(){
            var _this = this;
            this.xhr.onreadystatechange = function(){
                if(_this.xhr.readyState == 4 && _this.xhr.status == 200){
                    if(_this.xhr.status == 200){
                        if(_this.opts.dataType === ‘text‘ || _this.opts.dataType === ‘TEXT‘){
                            _this.opts.success && _this.opts.success(_this.xhr.responseText, ‘success‘, _this.xhr);
                        }else if(_this.opts.dataType === ‘xml‘ || _this.opts.dataType === ‘XML‘){
                            _this.opts.success && _this.opts.success(_this.xhr.responseXML, ‘success‘, _this.xhr);
                        }else if(_this.opts.dataType === ‘json‘ || _this.opts.dataType === ‘JSON‘){
                            _this.opts.success && _this.opts.success(JSON.parse(_this.xhr.responseText), ‘success‘, _this.xhr);
                        }
                    }else if(_this.xhr.status != 200){
                        _this.opts.error && _this.opts.error(_this.xhr, ‘error‘);
                    }
                }
            }
        },
        open: function(){
            if(this.opts.type === ‘GET‘ || this.opts.type === ‘get‘){
                var str = (typeof this.opts.data === ‘string‘) && this.opts.data || this.objectToString.call(this, this.opts.data),
                    url = (str === ‘‘) && this.opts.url || (this.opts.url.split(‘?‘)[0] + ‘?‘ + str);
                this.xhr.open(this.opts.type, url, this.opts.async);
            }else if(this.opts.type === ‘POST‘ || this.opts.type === ‘post‘){
                this.xhr.open(this.opts.type, this.opts.url.split(‘?‘)[0], this.opts.async);
            }
            return this;
        },
        send: function(){
            if(this.opts.type === ‘GET‘ || this.opts.type === ‘get‘){
                this.xhr.send();
            }else if(this.opts.type === ‘POST‘ || this.opts.type === ‘post‘){
                var str = (typeof this.opts.data === ‘string‘) && this.opts.data || this.objectToString.call(this, this.opts.data);
                this.xhr.setRequestHeader(‘content-type‘, ‘application/x-www-form-urlencoded‘);
                this.xhr.send(str);
            }
        },
        objectToString: function(data){
            if(typeof data !== ‘object‘) return data;
            var str = ‘‘;
            for(var prop in data){
                str += ‘&‘ + prop + ‘=‘ + data[prop];
            }
            return str.slice(1);
        }
    }
    exports.Ajax = Ajax;
})(window, document);

ajax.php

<?php

$c = $_REQUEST[‘c‘];
$arr = array(
    ‘a‘=>2014,
    ‘b‘=>array(‘c‘=>$c)
);
echo json_encode($arr);

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ajax</title>
</head>
<body>
    <script src="ajax.js"></script>
    <script>
        new Ajax().ajax({
            type: ‘get‘,
            url: ‘ajax.php?c=123‘,      // 如果是get方式并且url包含参数,其参数会被data替代
            // data: ‘c=456‘,           // data参数格式可以为字符串或对象
            // data: {c: 456},
            dataType: ‘json‘,
            async: false,
            success: function(data, status, xhr){
                console.log(data);
            },
            error: function(xhr, status){
                console.log(xhr);
            }
        });
        new Ajax().ajax({
            type: ‘post‘,
            url: ‘ajax.php?c=123‘,      // 如果是get方式并且url包含参数,其参数会被data替代
            data: ‘c=456‘,              // data参数格式可以为字符串或对象
            // data: {c: 456},
            dataType: ‘text‘,
            success: function(data, status, xhr){
                console.log(data);
            },
            error: function(xhr, status){
                console.log(xhr);
            }
        });
    </script>
</body>
</html>
时间: 2024-08-13 13:42:46

JavaScript封装Ajax(类JQuery中$.ajax()方法)的相关文章

封装一个类似jquery的ajax方法

//封装一个类似jquery的ajax方法,当传入参数,就可以发送ajax请求 //参数格式如下{ // type:"get"/"post", // dataType:"json"/"jsonp", // url:"地址", // data:{key:value} // success:function(){ // } // } //还需要一个跨域方法,可以访问远程服务器的数据 function myAja

通过原生js的ajax或jquery的ajax获取服务器的时间

在实际的业务逻辑中,经常是与时间相关的,而前端能获得的时间有两个:客户端的时间,服务器的时间.客户端时间通过 javascript中的Date对象可以获取,如 Java代码   var dt = new Date(); var tm = dt.getTime(); 那么tm就是客户端的时间,另外也可以通过对应的getFullYear(),getMonth(),getDate()取到对应的年月日等...但这个时间可靠吗?好吧,那取服务器时间吧经常用到的是后台写一个php,jsp,cgi,asp..

JavaScript的ajax与jQuery的ajax案例分析

先谈JavaScript的ajax,传输数据为json #############################################JavaScript ajax json########################################### 注意:由于要用到json的JSON.stringify()方法,需要引入json2.js库. html代码: <!DOCTYPE html><html lang="en"><head&g

Hybrid App开发之Ajax在JQuery中的应用

前言: 今天学习一下如何通过Ajax与服务器进行交互,并且学习一下如何在JQuery中使用. 首先先了解一下什么是ajax? AJAX即"Asynchronous,Javascript+XML"(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术.AJAX=异步JavaScript和XML(标准通用标记语言的子集).AJAX是一种用于创建快速动态网页的技术.通过在后台与服务器进行少量数据交换,AJAX可以使网页实现异步更新.这意味着可以在不重新加载整个网页的情

Js原生Ajax和Jquery的Ajax

一.Ajax概述 1.什么是同步,什么是异步 同步现象:客户端发送请求到服务器端,当服务器返回响应之前,客户端都处于等待卡死状态 异步现象:客户端发送请求到服务器端,无论服务器是否返回响应,客户端都可以随意做其他事情,不会被卡死 2.Ajax的运行原理 页面发起请求,会将请求发送给浏览器内核中的Ajax引擎,Ajax引擎会提交请求到服务器端,在这段时间里,客户端可以任意进行任意操作,直到服务器端将数据返回给Ajax引擎后,会触发你设置的事件,从而执行自定义的js逻辑代码完成某种页面1 功能. 二

js原生ajax与jquery的ajax的用法区别

什么是ajax和原理? AJAX 是一种用于创建快速动态网页的技术. 通过XmlHttpRequest对象来向服务器发异步请求,从服务器获得数据 XMLHttpRequest对象的基本属性: onreadtstatechange 每次状态改变所触发事件的时间处理程序. responseText 从服务器响应返回以字符串为形式的数据 responseXML 从服务器响应返回以XML(DOM兼容文档)数据对象 status 从服务器返回的数字代码 100-199 用于指定客户端应相应的某些动作. 2

Ajax相关(原生ajax,jQuery中ajax,axios)

1. get和post请求 从服务端获取数据:get请求 请求参数在地址栏中以urlencoded形式显示 格式:username=xcr&userAge=18 通过location.search可获取当前地址栏中 ? 及其后面的请求参数内容 可发送 2kb左右的数据 只能发送文本形式的数据 get请求可以被缓存,将地址保存,这个请求所携带的请求参数都将被保存 给服务端发送数据:post请求 post请求的参数在请求体中,不会在地址栏中体现,发送一些隐私数据时使用post请求发送,相对get请求

原生javascript实现Ajax和jQuery实现Ajax实例应用

这是我自己写的例子,希望对大家有帮助 使用了struts2,jdk1.6 1.实体类书写 public class Student { private String toid ; private String name ; private String sex ; public String getToid() { return toid ; } public void setToid(String toid) { this.toid = toid; } public String getNam

Ajax在jQuery中的应用

Ajax是Asynchronous JavaScript and XML的缩写,其核心是通过XMLHttpRequest对象,以一种异步的方式,向服务器发送数据请求,并通过该对象接收请求返回的数据,从而完成人机交互的数据操作.在jQuery中,有大量的函数与方法为Ajax技术提供支持. 1.load()方法 load(url,[data],[callback]) 参数url为被加载的页面地址,可选项[data]参数表示发送到服务器的数据,其格式为key/value.可选项[callback]参数