js文件(yizhi_ajax.js)
            1      /***  僅作為學(xué)習(xí)交流之用
            2         *  請您勿用于商業(yè)用途
            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對象創(chuàng)建失敗!");
           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("發(fā)送完畢");
           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("服務(wù)端返回狀態(tài)" + 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,如需相關(guān)jar包請自行搜索過著去官網(wǎng)下載)
          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: 小毅原創(chuàng)之---無聊時心血來潮純手寫ajax請求封裝類(ajax請求參數(shù)支持JSON對象)  回復(fù)  更多評論   

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

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

          Copyright © H2O

          主站蜘蛛池模板: 峨边| 浑源县| 厦门市| 麻江县| 都江堰市| 南阳市| 满城县| 农安县| 洛阳市| 柯坪县| 观塘区| 桂东县| 许昌市| 池州市| 上饶县| 扎赉特旗| 东宁县| 元氏县| 永平县| 江永县| 西乌珠穆沁旗| 蕲春县| 阳城县| 大荔县| 丁青县| 姜堰市| 江源县| 海口市| 广德县| 灵川县| 河间市| 庐江县| 西充县| 玛纳斯县| 麻江县| 津南区| 广昌县| 临朐县| 新化县| 英山县| 邵阳县|