您的位置:首页 > 其它

封装自己的ajax工具包

2015-09-20 01:17 302 查看
(1)js文件

// 创建request对象

function createXMLHttpRequest() {

try {

return new XMLHttpRequest();//大多数浏览器

} catch (e) {

try {

return ActvieXObject("Msxml2.XMLHTTP");//IE6.0

} catch (e) {

try {

return ActvieXObject("Microsoft.XMLHTTP");//IE5.5及更早版本

} catch (e) {

alert("哥们儿,您用的是什么浏览器啊?");

throw e;

}

}

}

}

/*

* option对象有如下属性

*/

/*请求方式*/method,

/*请求的url*/ url,

/*是否异步*/asyn,

/*请求体*/params,

/*回调方法*/callback,

/*服务器响应数据转换成什么类型*/type

function ajax(option) {

/*

* 1. 得到xmlHttp

*/

var xmlHttp = createXMLHttpRequest();

/*

* 2. 打开连接

*/

if(!option.method) {//默认为GET请求

option.method = "GET";

}

if(option.asyn == undefined) {//默认为异步处理

option.asyn = true;

}

xmlHttp.open(option.method, option.url, option.asyn);

/*

* 3. 判断是否为POST

*/

if("POST" == option.method) {

xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

}

/*

* 4. 发送请求

*/

xmlHttp.send(option.params);

/*

* 5. 注册监听

*/

xmlHttp.onreadystatechange = function() {

if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {//双重判断

var data;

// 获取服务器的响应数据,进行转换!

if(!option.type) {//如果type没有赋值,那么默认为文本

data = xmlHttp.responseText;

} else if(option.type == "xml") {

data = xmlHttp.responseXML;

} else if(option.type == "text") {

data = xmlHttp.responseText;

} else if(option.type == "json") {

var text = xmlHttp.responseText;

data = eval("(" + text + ")");

}

// 调用回调方法

option.callback(data);

}

};

};

(2)使用封装的ajax工具包

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

<head>

<title>My JSP 'json3.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">

<meta http-equiv="cache-control" content="no-cache">

<meta http-equiv="expires" content="0">

<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">

<meta http-equiv="description" content="This is my page">

<!--

<link rel="stylesheet" type="text/css" href="styles.css">

-->

<script type="text/javascript" src="<c:url value='/ajax-lib/ajaxutils.js'/>"></script>

<script type="text/javascript">

window.onload = function() {

var btn = document.getElementById("btn");

btn.onclick = function() {

/*

1. ajax

*/

ajax(

{

url:"<c:url value='/AServlet'/>",

type:"json",

callback:function(data) {

document.getElementById("h3").innerHTML = data.name + ", " + data.age + ", " + data.sex;

}

}

);

};

};

</script>

</head>

<body>

<%-- 点击按钮后,把服务器响应的数据显示到h3元素中 --%>

<button id="btn">点击这里</button>

<h1>显示自己封装的ajax小工具</h1>

<h3 id="h3"></h3>

</body>

</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: