自定义ajax小工具以及使用

function createXMLHttpRequest(){
        try{
            return new XMLHttpRequest();
        }catch(e){
            try{
                return new ActiveXObject("Msxml2.XMLHTTP");
            }catch(e){
                try{
                    return new ActiveXObject("Microsoft.XMLHTTP");
                }catch(e){
                    alert("哥们,你用的什么浏览器啊!");
                    throw e;
                }
            }
        }
}

/*option对象有如下属性:*/
/*请求方式method,*/
/*请求的地址url,*/
/*是否异步aysn,*/
/*请求体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);
            
        }
        
    };
}
ajaxutils.js
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <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="ajax-lib/ajaxutils.js"></script>
<script type="text/javascript">
    window.onload=function(){
        var btn=document.getElementsByTagName("button")[0];
        btn.onclick=function(){
            /*
             1.ajax
             */
             ajax(
                 {
                     url:"<c:url value='/AServlet'/>",
                     type:"json",
                     callback:function(data){
                         document.getElementsByTagName("h3")[0].innerHTML=data.name+" ,"+data.age+" ,"+data.sex;
                     }
                 }
             );
        };
    };
    
</script>
  </head>
  
  <body>
      <button>点击我</button>
     <h1>演示自己封装的小工具</h1>
     <h3></h3>
  </body>
</html>
json3.jsp
package cn.itcast.web.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AServlet extends HttpServlet{
    
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String str="{\"name\":\"zhangSan\",\"age\":18,\"sex\":\"male\"}";
        resp.getWriter().print(str);
    }

}
AServlet

 

posted @ 2016-08-11 21:00  guodaxia  阅读(227)  评论(0编辑  收藏  举报