JavaScript XMLHttpRequest使用介绍

        开发各种各样的Web应用程序,Ajax几乎是必不可少的了,在众多的工具中,可以使用 jQuery 中的$.ajax(),也可是在MVC中使用封装好的相关的ajax库。现在我的例子是使用 JavaScript 中XMLHttpRequest来将信息发送到服务器,这就是ajax技术的核心。这里是个小例子,好记性不如烂笔头,我在这边记录下来,以便以后查阅,也给需要的同学们提供点参考。

第一部分:首先来看一下简单的网页。

  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2.   
  3. <html xmlns="http://www.w3.org/1999/xhtml">  
  4. <head runat="server">  
  5.     <title>XMLHttpRequest例子</title>  
  6. </head>  
  7. <body>  
  8.     <form id="form1" runat="server" action="WebForm2.aspx">  
  9.     <div>  
  10.         <input type="button" value="调用WebService" onclick="callServer()"/>  
  11.         <span id="showmsg"></span>  
  12.   
  13.         <input type="submit" value="提交数据"/>  
  14.         <input type="text" name="ID" />  
  15.     </div>  
  16.     </form>  
  17. </body>  
  18. </html>  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>XMLHttpRequest例子</title>
</head>
<body>
    <form id="form1" runat="server" action="WebForm2.aspx">
    <div>
        <input type="button" value="调用WebService" οnclick="callServer()"/>
        <span id="showmsg"></span>

        <input type="submit" value="提交数据"/>
        <input type="text" name="ID" />
    </div>
    </form>
</body>
</html>

下面是调用callSever()方法时,需要执行的JavaScript方法。

首先是创建一个XMLHttpRequest对象,不同的浏览器创建该对象会不一样,主要是IE和其他浏览器的差别

[javascript] view plain copy
print ?
  1. function createHttpRequest() {  
  2.             var httpRequest = null;  
  3.             //针对IE7,火狐,谷歌等其他浏览器  
  4.             if (window.XMLHttpRequest) {  
  5.                 httpRequest = new XMLHttpRequest();  
  6.                 //针对某些特定版本的mozillar浏览器的BUG进行修正  
  7.                 /* 
  8.                     如果来自服务器的响应没有 XML mime-type 头部,则一些版本的 Mozilla 浏览器不能正常运行。 
  9.                     对于这种情况,httpRequest.overrideMimeType('text/xml'); 语句将覆盖发送给服务器的头部,强制 text/xml 作为 mime-type。 
  10.                 */  
  11.                 if (httpRequest.overrideMimeType) {  
  12.                     httpRequest.overrideMimeType("text/xml");  
  13.                 }  
  14.                 return httpRequest;  
  15.             }  
  16.             //针对IE5,IE6浏览器  
  17.             if (window.ActiveXObject) {  
  18.                 try {  
function createHttpRequest() {
            var httpRequest = null;
            //针对IE7,火狐,谷歌等其他浏览器
            if (window.XMLHttpRequest) {
                httpRequest = new XMLHttpRequest();
                //针对某些特定版本的mozillar浏览器的BUG进行修正
                /*
                    如果来自服务器的响应没有 XML mime-type 头部,则一些版本的 Mozilla 浏览器不能正常运行。
                    对于这种情况,httpRequest.overrideMimeType('text/xml'); 语句将覆盖发送给服务器的头部,强制 text/xml 作为 mime-type。
                */
                if (httpRequest.overrideMimeType) {
                    httpRequest.overrideMimeType("text/xml");
                }
                return httpRequest;
            }
            //针对IE5,IE6浏览器
            if (window.ActiveXObject) {
                try {
[javascript] view plain copy
print ?
  1.            httpRequest = new ActiveXObject("Microsoft.XMLHTTP");  
  2.         } catch (e) {  
  3.             try {  
  4.                 httpRequest = new ActiveXObject("Msxml2.XMLHTTP");  
  5.             } catch (ex) {  
  6.                 alert("创建XMLHTTPRequest对象失败!");  
  7.             }  
  8.         }  
  9.     }  
  10.     return httpRequest;  
  11. }  
                   httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e) {
                    try {
                        httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
                    } catch (ex) {
                        alert("创建XMLHTTPRequest对象失败!");
                    }
                }
            }
            return httpRequest;
        }

下面是点击按钮调用的callServer方法

[javascript] view plain copy
print ?
  1. function callServer() {  
  2.             var http_request = createHttpRequest();  
  3.             if (http_request == null) {  
  4.                 return;  
  5.             }  
  6.             /* 
  7.             我们的实例在 open() 的第三个参数中使用了 "true"。 
  8.             该参数规定请求是否异步处理。 
  9.             True 表示脚本会在 send() 方法之后继续执行,而不等待来自服务器的响应。 
  10.             onreadystatechange 事件使代码复杂化了。但是这是在没有得到服务器响应的情况下,防止代码停止的最安全的方法。 
  11.             通过把该参数设置为 "false",可以省去额外的 onreadystatechange 代码。如果在请求失败时是否执行其余的代码无关紧要,那么可以使用这个参数。 
  12.              */  
  13.             http_request.open("GET""WebService1.asmx/HelloWorld?msg=gong"true);  
  14.             //向服务器发送请求  
  15.             http_request.send();  
  16.             //当readyState属性改变的时候调用的事件句柄函数。当 readyState 为 3 时,它也可能调用多次。  
  17.             http_request.onreadystatechange = function () {  
  18.                 //HTTP 请求的状态.当一个 XMLHttpRequest 初次创建时,这个属性的值从 0 开始,直到接收到完整的 HTTP 响应,这个值增加到 4  
  19.                 if (http_request.readyState == 4) {  
  20.                     //指定了请求的 HTTP 的状态代码(200表示正常,404表示未找到)  
  21.                     if (http_request.status == 200) {  
  22.                         document.getElementById("showmsg").innerHTML = http_request.responseText;  
  23.                     }  
  24.                 }  
  25.             }  
  26.   
  27.             /* 
  28.             当前是使用GET方式提交数据,数据都放在URL后面 
  29.             而POST方法是把要发送的东西放到HTTP HEAD里面,这样最大可以发送2G的数据, 
  30.             但用POST方法的时候一定要先使用setRequestHeader方法把Content-Type设置为"application/x-www-form-urlencoded", 
  31.             */  
  32.             content = "user=" + encodeURIComponent("gongxiongwei");  
  33.             http_request.open("POST""WebForm2.aspx"false);  
  34.             http_request.setRequestHeader("Content-Length", content.length);  
  35.             http_request.setRequestHeader("Content-Type""application/x-www-form-urlencoded");  
  36.             http_request.send(content);  
  37.         }  
function callServer() {
            var http_request = createHttpRequest();
            if (http_request == null) {
                return;
            }
            /*
            我们的实例在 open() 的第三个参数中使用了 "true"。
            该参数规定请求是否异步处理。
            True 表示脚本会在 send() 方法之后继续执行,而不等待来自服务器的响应。
            onreadystatechange 事件使代码复杂化了。但是这是在没有得到服务器响应的情况下,防止代码停止的最安全的方法。
            通过把该参数设置为 "false",可以省去额外的 onreadystatechange 代码。如果在请求失败时是否执行其余的代码无关紧要,那么可以使用这个参数。
             */
            http_request.open("GET", "WebService1.asmx/HelloWorld?msg=gong", true);
            //向服务器发送请求
            http_request.send();
            //当readyState属性改变的时候调用的事件句柄函数。当 readyState 为 3 时,它也可能调用多次。
            http_request.onreadystatechange = function () {
                //HTTP 请求的状态.当一个 XMLHttpRequest 初次创建时,这个属性的值从 0 开始,直到接收到完整的 HTTP 响应,这个值增加到 4
                if (http_request.readyState == 4) {
                    //指定了请求的 HTTP 的状态代码(200表示正常,404表示未找到)
                    if (http_request.status == 200) {
                        document.getElementById("showmsg").innerHTML = http_request.responseText;
                    }
                }
            }

            /*
            当前是使用GET方式提交数据,数据都放在URL后面
            而POST方法是把要发送的东西放到HTTP HEAD里面,这样最大可以发送2G的数据,
            但用POST方法的时候一定要先使用setRequestHeader方法把Content-Type设置为"application/x-www-form-urlencoded",
            */
            content = "user=" + encodeURIComponent("gongxiongwei");
            http_request.open("POST", "WebForm2.aspx", false);
            http_request.setRequestHeader("Content-Length", content.length);
            http_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            http_request.send(content);
        }

在这个例子中,请求的是WebService中的HelloWorld方法,GET方式通过在URL后面添加参数的形式往服务器端发送相关的参数。

注意:有时使用GET方式提交时会出现URL以XX/非法路径结束的提示,需要在WebConfig中添加如下节点即可

  1. <system.web>  
  2.         <compilation debug="true" targetFramework="4.0" />  
  3.         <webServices>  
  4.             <protocols>  
  5.                 <add name="HttpGet"/>  
  6.                 <add name="HttpPost"/>  
  7.             </protocols>  
  8.         </webServices>  
  9.     </system.web>  
<system.web>
        <compilation debug="true" targetFramework="4.0" />
		<webServices>
			<protocols>
				<add name="HttpGet"/>
				<add name="HttpPost"/>
			</protocols>
		</webServices>
    </system.web>
[csharp] view plain copy
print ?
  1. /// <summary>  
  2.     /// WebService1 的摘要说明  
  3.     /// </summary>  
  4.     [WebService(Namespace = "http://tempuri.org/")]  
  5.     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]  
  6.     [System.ComponentModel.ToolboxItem(false)]  
  7.     // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。  
  8.     [System.Web.Script.Services.ScriptService]  
  9.     public class WebService1 : System.Web.Services.WebService  
  10.     {  
  11.   
  12.         [WebMethod]  
  13.         public string HelloWorld(string msg)  
  14.         {  
  15.             return "Hello World " + msg;  
  16.         }  
  17. }  
/// <summary>
    /// WebService1 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // 若要允许使用 ASP.NET AJAX 从脚本中调用此 Web 服务,请取消对下行的注释。
    [System.Web.Script.Services.ScriptService]
    public class WebService1 : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld(string msg)
        {
            return "Hello World " + msg;
        }
}

执行以后如图所示:



----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

如果以POST方式向服务器提交数据的时候需要构造HTTP Header消息头(上面代码中有)

下面介绍在.NET中如何不使用服务器控件来向页面提交数据

假设当前是在WebForm1.aspx页面,需要往WebForm2.aspx页面传递数据。

  1. <form id="form1" runat="server" action="WebForm2.aspx">  
  2.     <div>  
  3.         <input type="button" value="调用WebService" onclick="callServer()"/>  
  4.         <span id="showmsg"></span>  
  5.   
  6.         <input type="submit" value="提交数据"/>  
  7.         <input type="text" name="ID" />  
  8.     </div>  
  9.     </form>  
<form id="form1" runat="server" action="WebForm2.aspx">
    <div>
        <input type="button" value="调用WebService" οnclick="callServer()"/>
        <span id="showmsg"></span>

        <input type="submit" value="提交数据"/>
        <input type="text" name="ID" />
    </div>
    </form>

点击submit按钮(提交数据),会将<input type='text' name='ID' />中的数据提交到WebForm2.aspx,POST会使用Form进行数据的提交

在C#后台页面WebForm2.aspx页面取出提交的数据

[csharp] view plain copy
print ?
  1. if (!IsPostBack)  
  2.             {  
  3.                 //HTML控件的Name属性(不是ID)  
  4.                 string post_value = Request["ID"].ToString();  
  5.                 Label1.Text = post_value;  
  6.             }  
if (!IsPostBack)
            {
                //HTML控件的Name属性(不是ID)
                string post_value = Request["ID"].ToString();
                Label1.Text = post_value;
            }

通过HttP Post方式提交文件到服务器

首先客户端的代码如下ClientPage.aspx

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ClientPage.aspx.cs" Inherits="ASP.NET实验项目.ClientPage" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title>通过表单提交数据</title>  
  8.     <script language="javascript" type="text/javascript">  
  9.         //注意由于IE对文件的安全性设置:文件上传控件必须自己手动点击之后才能触发form.submit()进行表单的提交  
  10.         function PostHttpFile() {  
  11.             var uploadControl = document.getElementById("myFile");  
  12.             uploadControl.select(); //先选中该控件  
  13.             //在IE下面要使焦点离开上传控件才能取到文件的路径  
  14.             uploadControl.blur();  
  15.             var filePath = window.document.selection.createRange().text;  
  16.             //进行文件的上传  
  17.             if (filePath == "") {  
  18.                 return;  
  19.             }  
  20.             window.form1.submit();  
  21.         }  
  22.     </script>  
  23. </head>  
  24. <body>  
  25.     <%--通过Post方式提交文件 enctype="multipart/form-data"或者设置 runat="server"即可以传送文件--%>  
  26.     <form id="form1" method="post" action="Server.aspx" enctype="multipart/form-data">  
  27.         <input type="file" id="myFile" onchange="PostHttpFile()" name="myFile"/>  
  28.         <%--<input type="submit" value="提交文件" />--%>  
  29.     </form>  
  30. </body>  
  31. </html>  
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ClientPage.aspx.cs" Inherits="ASP.NET实验项目.ClientPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>通过表单提交数据</title>
    <script language="javascript" type="text/javascript">
        //注意由于IE对文件的安全性设置:文件上传控件必须自己手动点击之后才能触发form.submit()进行表单的提交
        function PostHttpFile() {
            var uploadControl = document.getElementById("myFile");
            uploadControl.select(); //先选中该控件
            //在IE下面要使焦点离开上传控件才能取到文件的路径
            uploadControl.blur();
            var filePath = window.document.selection.createRange().text;
            //进行文件的上传
            if (filePath == "") {
                return;
            }
            window.form1.submit();
        }
    </script>
</head>
<body>
    <%--通过Post方式提交文件 enctype="multipart/form-data"或者设置 runat="server"即可以传送文件--%>
    <form id="form1" method="post" action="Server.aspx" enctype="multipart/form-data">
        <input type="file" id="myFile" οnchange="PostHttpFile()" name="myFile"/>
        <%--<input type="submit" value="提交文件" />--%>
    </form>
</body>
</html>

然后在服务端写接收文件时的代码 Server.aspx

[csharp] view plain copy
print ?
  1. protected void Page_Load(object sender, EventArgs e)  
  2.         {  
  3.             //接收客户端Post过来的文件  
  4.             if (Request.Files.Count >= 1)  
  5.             {  
  6.                 //可以通过Request.Files[0]来获取上传的文件也可以根据上传文件的Name属性来获取  
  7.                 HttpPostedFile postFile = Request.Files["myFile"];  
  8.                 string fileName = postFile.FileName;  
  9.                 //将Post过来的文件进行到指定的路径  
  10.                 postFile.SaveAs(Server.MapPath("~/Uploads/" + fileName));  
  11.             }  
  12.         }  
protected void Page_Load(object sender, EventArgs e)
        {
            //接收客户端Post过来的文件
            if (Request.Files.Count >= 1)
            {
                //可以通过Request.Files[0]来获取上传的文件也可以根据上传文件的Name属性来获取
                HttpPostedFile postFile = Request.Files["myFile"];
                string fileName = postFile.FileName;
                //将Post过来的文件进行到指定的路径
                postFile.SaveAs(Server.MapPath("~/Uploads/" + fileName));
            }
        }

这样文件就上传成功了

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值