js文件(yizhi_ajax.js)
  1      /***  仅作为学习交流之用
  2         *  请您勿用于商业用途
  3         */
 
  4      var yizhi_ajax ={
  5          xhr:false,
  6          url:"",
  7          method:"post",
  8          toString:Object.prototype.toString,
  9          isArray:function( obj ) {
 10            return this.toString.call(obj) === "[object Array]";
 11        }
,
 12        isFunction:function( obj ) {
 13            return this.toString.call(obj) === "[object Function]";
 14        }
,
 15        each:function( object, callback, args ) {
 16            var name, i = 0, length = object.length;
 17            if ( args ) {
 18                if ( length === undefined ) {
 19                    for ( name in object )
 20                        if ( callback.apply( object[ name ], args ) === false )
 21                            break;
 22                }
 else
 23                    for ( ; i < length; )
 24                        if ( callback.apply( object[ i++ ], args ) === false )
 25                            break;
 26            }
 else {
 27                if ( length === undefined ) {
 28                    for ( name in object )
 29                        if ( callback.call( object[ name ], name, object[ name ] ) === false )
 30                            break;
 31                }
 else
 32                    for ( var value = object[0];
 33                        i < length && callback.call( value, i, value ) !== false; value = object[++i] ){}
 34            }

 35    
 36            return object;
 37        }
,
 38          param:function(a){
 39              var s = [ ];
 40            function add( key, value ){
 41                s[ s.length ] = encodeURIComponent(key) + '=+ encodeURIComponent(value);
 42            }
;
 43            if ( this.isArray(a))
 44                this.each( a, function(){
 45                    add( this.name, this.value );
 46                }
);
 47    
 48            else
 49                for ( var j in a )
 50                    if ( this.isArray(a[j]) )
 51                        this.each( a[j], function(){
 52                            add( j, this );
 53                        }
);
 54                    else
 55                        add( j, this.isFunction(a[j]) ? a[j]() : a[j] );
 56            return s.join("&").replace(/%20/g, "+");
 57          }
,
 58          showMsg:true,
 59          getXhr:function(){
 60                  if(this.xhr==false){
 61                  try{
 62                      this.xhr = new ActiveXObject("Microsoft.XMLHTTP");
 63                  }
catch(e){
 64                      try{
 65                          this.xhr = new ActiveXObject("Msxml2.XMLHTTP");
 66                      }
catch(e){
 67                          alert("xhr对象创建失败!");
 68                      }

 69                  }

 70              }

 71              return this.xhr;
 72          }
,
 73          send:function(requestUrl,parameters,callBack){
 74              if(this.xhr==false){
 75                  this.getXhr();
 76              requestUrl+=("?"+new Date().getTime()); //利用随即生成的时间解决缓存问题
 77              this.xhr.open(this.method,requestUrl,true);
 78              this.xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded;charset=UTF-8;');
 79              this.xhr.send(this.param(parameters));    
 80              this.xhr.onreadystatechange=function(){
 81                  if(yizhi_ajax.xhr.readyState ==4){
 82                      if(this.showMsg){
 83                          alert("发送完毕");
 84                      }

 85                      if(yizhi_ajax.xhr.status==200){
 86                          if(this.showMsg){
 87                              alert("请求成功并完成!");
 88                          }

 89                          callBack(yizhi_ajax.xhr);
 90                          yizhi_ajax.xhr=false;
 91                      }
else{
 92                          if(this.showMsg){
 93                              alert("服务端返回状态" + yizhi_ajax.xhr.statusText);
 94                          }

 95                      }

 96                  }

 97              }

 98          }

 99      }

100          
101  }

index.jsp
 1
 2
 3<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 4<html>
 5  <head>
 6    
 7    <title>无聊就要涮锅子</title>
 8    <meta http-equiv="content-type" content="text/html;charset=UTF-8">
 9    <meta http-equiv="pragma" content="no-cache">
10    <meta http-equiv="cache-control" content="no-cache">
11    <meta http-equiv="expires" content="0">    
12  </head>
13  <script type="text/javascript" src="js/yizhi_ajax.js"></script>
14  <script type="text/javascript">    
15       var check=function(){
16      var param={
17          name:document.getElementById("uname").value
18      }

19      yizhi_ajax.send("http://127.0.0.1:8080/test/servlet/test",param,function(xhr)
20          {
21              try{
22                  var response =eval("(" + xhr.responseText + ")"); 
23              if(response.is=="yes"){
24                  alert("果然你是死锅子,唰,刷刷刷!!!!!!!!!!!!!唰锅子就是爽 O(∩_∩)O哈哈~");
25              }
else{
26                  alert("你真TMD太令我失望了。。。╮(╯▽╰)╭哎。。。");
27              }

28              }
catch(e){
29              }

30          }

31      );
32      
33  }

34  
</script>
35  <body>
36    请输入您的姓名:<input id="uname">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
37        <input type="button" value="你是死锅子吗?" onclick="check();">
38       
39  </body>
40</html>
41

servlet文件(test.java  URL映射为:/servlet/test   本例子用了json2.3,如需相关jar包请自行搜索过着去官网下载)
package com.yz.test;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

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

import net.sf.json.JSONObject;

public class test extends HttpServlet {


    
public void doGet(HttpServletRequest request, HttpServletResponse response)
            
throws ServletException, IOException {

        doPost(request,response);
    }


    
public void doPost(HttpServletRequest request, HttpServletResponse response)
            
throws ServletException, IOException {
        request.setCharacterEncoding(
"UTF-8");
        response.setContentType(
"text/html;charset=UTF-8");
        PrintWriter out 
= response.getWriter();
        
try {
            Map map 
= new HashMap();
            
if("郭照友".equals(URLDecoder.decode(request.getParameter("name")))){
                map.put(
"is","yes");
            }
else{
                map.put(
"is","no");
            }

            JSONObject json 
= JSONObject.fromObject(map);
            out.println(json);
        }
 catch (Exception e) {
        }

        out.flush();
        out.close();
    }

}

Feedback

# re: 小毅原创之---无聊时心血来潮纯手写ajax请求封装类(ajax请求参数支持JSON对象)  回复  更多评论   

2010-10-19 18:07 by caikeyter
太烂了

只有注册用户登录后才能发表评论。


网站导航:
 

posts - 0, comments - 21, trackbacks - 0, articles - 101

Copyright © H2O