ajax javascript post 方法实现(与C#混合使用)

先建一个JS文件命名为Ajax.js


function CreateXMLHttpRequest()//这里是构造XMLHttpRequest对象的方法
... {
varxmlHttpRequest=null;//这里是大家都常用的IE,firefox中取得XMLHttpRequest对象的方法
try
...{

xmlHttpRequest
=newXMLHttpRequest();
}

catch(e)
...{
try
...{
xmlHttpRequest
=newActiveXObject("Msxml2.XMLHTTP");
}

catch(e)
...{
xmlHttp
=newActiveXObject("Microsoft.XMLHTTP");

}

}


returnxmlHttpRequest;
}


function AjaxSubmit(url,data,changeFunction)//url指定跳转页,data是要post的数据。changeFunction类似于函数指针
... {
varxmlHttpResquest=CreateXMLHttpRequest();
xmlHttpResquest.open(
"post",url,true);
xmlHttpResquest.setRequestHeader(
"content-length",data.length);
xmlHttpResquest.setRequestHeader(
"Content-Type","application/x-www-form-urlencoded");
xmlHttpResquest.send(data);

xmlHttpResquest.onreadystatechange
=function()
...{
if(xmlHttpResquest.readyState==4)
...{
try
...{
if(xmlHttpResquest.status==200)
...{
alert(xmlHttpResquest.responseText);
changeFunction(xmlHttpResquest.responseText);//这里可以调用想要的函数
}

}

catch(e)
...{
alert(
"over");
}

}

}


}

比如我有一个页面叫Start.html或者Start.aspx

< head >
< title > UntitledPage </ title >
< scripttype = " text/javascript " src = " Ajax.js " ></ script >
</ head >
< body >
< scriptlanguage = " javascript " type = " text/javascript " >
AjaxSubmit(
" Ajax.aspx " , " nodesInfoTxt=hh " ,InitForAjax);
// Ajax.aspx是接受数据的页面,InitForAjax是本页面接受到回发数据后要执行的函数。其他的为数据。
functionInitForAjax(str)
... {
alert(str);
}

</ script >
</ body >

一般.net生成的aspx页面是这样写的

<% ... @PageLanguage="C#"AutoEventWireup="true"CodeFile="Ajax.aspx.cs"Inherits="Ajax" %>

<! DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >

< html xmlns ="http://www.w3.org/1999/xhtml" >
< head runat ="server" >

</ head >
< body >
< form id ="form1" runat ="server" >
< div >

</ div >
</ form >
</ body >


</ html >

下面为了回传数据仅仅是数据而不是连同整个页面一起发送过来。

在Ajax.aspx页面这样这样写(这一句就足够了)

<% @PageLanguage = " C# " AutoEventWireup = " true " CodeFile = " Ajax.aspx.cs " Inherits = " Ajax " %>

然后在它的后置类也就是Ajax.aspx.cs中这样写:

// 前面省略一些代码生成的东西
protected void Page_Load( object sender,EventArgse)
... {
if(Request.Form["nodesInfoTxt"]!=null)
stringnodes=Request.Form["nodesInfoTxt"].ToString();
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = "text/xml";
Response.write("bye");
}

你在本函数结束处设一个断点,是否nodes就已经被赋值了呢?然后继续执行你的页面就会跳出一个bye的提示框。这就是Ajax异步传输。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值