---
title: "通过js发送请求的几种方法"
author: "feohoo"
date: "2011-12-19T15:11:12Z"
tags: []
categories: ["Web前端"]
slug: "js"
draft: false
lastmod: "2011-12-19T15:11:12Z"
id: 1316826
url: "https://feohoo.iteye.com/blog/1316826"
---

var httpAdapter;  
    //创建一个httpAdapter对象  
    function GethttpAdapterRequest()  
    {  
        //httpAdapter = window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new httpAdapterRequest();  
         return window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : new XMLHttpRequest();  
    }  
     
    //以Get方式发送请求,默认Content-Type为"text/xml; charset=gb2312"  
    this.GetData = function(url)  
    {  
        httpAdapter = GethttpAdapterRequest();  
   httpAdapter.Open("GET",url, false);  
   httpAdapter.SetRequestHeader ("Content-Type","text/xml; charset=gb2312");  
//   httpAdapter.SetRequestHeader ("SOAPAction","[http://tempuri.org/getStr](http://tempuri.org/getStr)");  
   httpAdapter.Send(context);  
   return httpAdapter;  
    }  
     
    //以POST方式发送请求,默认Content-Type为"application/x-www-form-urlencoded"  
    this.PostData = function (url,context)  
    {  
        httpAdapter = GethttpAdapterRequest();  
        httpAdapter.Open("POST",url, false);  
   httpAdapter.setRequestHeader("Content-Type","application/x-www-form-urlencoded");  
//   httpAdapter.SetRequestHeader ("SOAPAction","[http://tempuri.org/getStr](http://tempuri.org/getStr)");  
   httpAdapter.Send(context);  
   return httpAdapter;  
    }  
     
     
    this.GetDataInAsync = function (url,callbackMethod)  
    {  
        httpAdapter = GethttpAdapterRequest();  
   httpAdapter.Open("GET",url, true);  
   httpAdapter.SetRequestHeader ("Content-Type","text/xml; charset=gb2312");  
//   httpAdapter.SetRequestHeader ("SOAPAction","[http://tempuri.org/getStr](http://tempuri.org/getStr)");  
   httpAdapter.Send(context);  
   httpAdapter.onreadystatechange = callbackMethod;  
    }  
     
    this.PostDataInAsync = function (url,context,callbackMethod)  
    {  
        httpAdapter = GethttpAdapterRequest();  
        httpAdapter.Open("POST",url, true);  
   httpAdapter.setRequestHeader("Content-Type","application/x-www-form-urlencoded");  
//   httpAdapter.SetRequestHeader ("SOAPAction","[http://tempuri.org/getStr](http://tempuri.org/getStr)");  
   httpAdapter.Send(context);  
   httpAdapter.onreadystatechange = callbackMethod;  
    }  
     
    //获取指定地址的域名  
    this.GetHost = function(url)  
    {  
        var host = "null";  
        var ArryHost=new Array();  
        if(typeof url == "undefined"|| null == url)  
        {  
            url = window.location.href;  
        }  
        var regex = /.\*\\:\\/\\/(\[^\\/]\*).\*/;  
        var match = url.match(regex);  
        if(typeof match != "undefined" && null != match)  
        {  
            ArryHost = match\[1].split(/:/);  
            host =ArryHost\[0];  
        }  
        return host;  
    }  
     
    //获取当前地址的域名  
    this.GetLocalHost=function()  
    {  
       return GetHost(document.URL);  
    }

 

  以前每次写AJAX请求总要写好几个JS函数，包括创建XMLHttpRequest对象、发送请求、成功后的处理函数和失败后的处理函数，下面的JS是把这些东西重构之后参数化的形式，然后放到一个单独的net.js里，后续使用只需引入这个JS，然后新建相应的对象和处理函数即可，可以直接拿来使用

   var net = new Object();  
   net.READY\_STATE\_UNINITIALIZED = 0;  
   net.READY\_STATE\_LOADING = 1;  
   net.READY\_STATE\_LOADED = 2;  
   net.READY\_STATE\_INTERACTIVE = 3;  
   net.READY\_STATE\_COMPLETE = 4;

 

   

   net.ContentLoader = function(url,onload,onerror,method,params,contentType)  
   {

    this.req = null;  
    this.onload = onload;  
    this.onerror = (onerror) ? onerror : this.defaultError;  
    this.loadXMLDoc(url,method,params,contentType);  
   }

 

   net.ContentLoader.prototype = {  
   

   onReadyState: function(){  
        
     var req = this.req;  
     var ready = req.readyState;  
     if(ready == net.READY\_STATE\_COMPLETE)  
     {  
        var httpStatus = req.status;  
     if(httpStatus == 200 || httpStatus == 0)  
         this.onload.call(this);  
        else  
         this.onerror.call(this);  
            }  
    },

    defaultError: function(){  
            
     alert("error in fetching data!! readyState=="+this.req.readyState+"\\n\\nstatus="+this.req.status  
          +" \\n\\nheaders"+this.req.getAllResponseHeaders());

    }

 

   }

 

   net.ContentLoader.prototype.loadXMLDoc = function(url,method,params,contentType){

     if(!method)  //如果没有传入method 参数值，则默认为GET  
     {  
         method = "GET";  
     }  
     if (!contentType && method=="POST"){  
         contentType="application/x-www-form-urlencoded;";  
     }  
          
     if(window.XMLHttpRequest)  
     {  
        this.req = new XMLHttpRequest();  
      }  
     else if(window.ActiveXObject)  
     {  
        this.req = new ActiveXObject("Microsoft.XMLHTTP");  
     }  
     if(this.req)  
     {

          
       try{  
            var loader = this;     
            this.req.onreadystatechange = function(){  
                loader.onReadyState.call(loader);  
            }  
            this.req.open(method,url,true);   
            //POST方法需要设置的属性  
            if (contentType){  
               this.req.setRequestHeader("Content-Type", contentType);  
            }   
            this.req.send(params);  
       
       }catch(err)  
      {   
          this.onerror.call(this);  
      }  
    }  
 }

 

    代码内容不在做过多解释，如果你对JS面向对象和prototype不太熟悉的话请查阅相关书籍，下面演示如何使用:

1. 把上述内容单独放到一个文件net.js（名称可自己定义)

2\. 在要使用的JSP页面上引入这个net.js  即  &lt;script src="net.js"&gt; &lt;/script&gt;

3\. 发送请求GET方式

   new  net.ContentLoader("[http://localhost:8080/CfgWeb/AppLogin.do",getMessage](http://localhost:8080/CfgWeb/AppLogin.do));  

   其中第一个参数是请求的后台程序地址，第二个参数是请求成功后的处理函数（自己定义）

   后面的参数可省略，也可自己添加第三个参数（请求不成功的处理函数）

   function getMessage()

   {

        alert(this.req.responseText);  //简单的输出返回结果的字符串形式

        alert(this.req.responseXML);   //XML形式，后面就根据你的需要解析这个XML了

   }

4\. 发送POST请求

   new net.ContentLoader("[http://localhost:8080/CfgWeb/AppLogin.do?formAction=autoComplete",getMessage,null,"POST","&userName=wangwei&password=123](http://localhost:8080/CfgWeb/AppLogin.do?formAction=autoComplete)" );

   function getMessage()

   {

        alert(this.req.responseText);  //简单的输出返回结果的字符串形式

        alert(this.req.responseXML);   //XML形式，后面就根据你的需要解析这个XML了

   }