您的位置:首页 > 理论基础 > 计算机网络

JavaScript XMLHttpRequest使用介绍

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

[html]
view plain
copy

print?

<!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" onclick="callServer()"/>  
        <span id="showmsg"></span>  
  
        <input type="submit" value="提交数据"/>  
        <input type="text" name="ID" />  
    </div>  
    </form>  
</body>  
</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" onclick="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?

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 {  



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?

           httpRequest = new ActiveXObject("Microsoft.XMLHTTP");  
        } catch (e) {  
            try {  
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");  
            } catch (ex) {  
                alert("创建XMLHTTPRequest对象失败!");  
            }  
        }  
    }  
    return httpRequest;  
}  



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?

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);  
        }  



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中添加如下节点即可

[html]
view plain
copy

print?

<system.web>  
        <compilation debug="true" targetFramework="4.0" />  
        <webServices>  
            <protocols>  
                <add name="HttpGet"/>  
                <add name="HttpPost"/>  
            </protocols>  
        </webServices>  
    </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?

/// <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;  
        }  
}  



/// <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页面传递数据。

[html]
view plain
copy

print?

<form id="form1" runat="server" action="WebForm2.aspx">  
    <div>  
        <input type="button" value="调用WebService" onclick="callServer()"/>  
        <span id="showmsg"></span>  
  
        <input type="submit" value="提交数据"/>  
        <input type="text" name="ID" />  
    </div>  
    </form>  



<form id="form1" runat="server" action="WebForm2.aspx">
<div>
<input type="button" value="调用WebService" onclick="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?

if (!IsPostBack)  
            {  
                //HTML控件的Name属性(不是ID)  
                string post_value = Request["ID"].ToString();  
                Label1.Text = post_value;  
            }  



if (!IsPostBack)
{
//HTML控件的Name属性(不是ID)
string post_value = Request["ID"].ToString();
Label1.Text = post_value;
}

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

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

[html]
view plain
copy

print?

<%@ 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" onchange="PostHttpFile()" name="myFile"/>  
        <%--<input type="submit" value="提交文件" />--%>  
    </form>  
</body>  
</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" onchange="PostHttpFile()" name="myFile"/>
<%--<input type="submit" value="提交文件" />--%>
</form>
</body>
</html>

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

[csharp]
view plain
copy

print?

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));  
            }  
        }  



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));
}
}

这样文件就上传成功了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: