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

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



function CreateXMLHttpRequest()//这里是构造XMLHttpRequest对象的方法
… {

var xmlHttpRequest = null ;//这里是大家都常用的IE,firefox中取得XMLHttpRequest对象的方法

try
… {


xmlHttpRequest = new XMLHttpRequest();
}

catch (e)
… {

try
… {

xmlHttpRequest = new ActiveXObject( “ Msxml2.XMLHTTP “ );
}

catch (e)
… {

xmlHttp = new ActiveXObject( “ Microsoft.XMLHTTP “ );

}
}


return xmlHttpRequest;
}


function AjaxSubmit(url,data,changeFunction)//url指定跳转页,data是要post的数据。changeFu
nction类似于函数指针
… {

var xmlHttpResquest = 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 > Untitled Page </ title >
<
script type = “ text/javascript “ src = “ Ajax.js “ ></ script >
</
head >
<
body >
<
script language = “ javascript “ type = “ text/javascript “ >

AjaxSubmit( “ Ajax.aspx “ , “ nodesInfoTxt=hh “ ,InitForAjax);
//
Ajax.aspx是接受数据的页面,InitForAjax是本页面接受到回发数据后要执行的函数。其他的为数据。

function InitForAjax(str)
… {

alert(str);
}
</
script >
</
body >

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

<% … @ Page Language = “ C# “ AutoEventWireup =
“ true “ CodeFile = “ Ajax.aspx.cs “ Inherits = “ Ajax “ %>

<!
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” >

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

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


</
html >

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

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

<%
@ Page Language = “ C# “ AutoEventWireup = “ true “ CodeFile = “
Ajax.aspx.cs “ Inherits = “ Ajax “ %>

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

//
前面省略一些代码生成的东西

protected void Page_Load( object sender, EventArgs e)
… {

if (Request.Form[ “ nodesInfoTxt “ ] != null )

string nodes = Request.Form[ “ nodesInfoTxt “ ].ToString();

Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = “text/xml”;
Response.write(“bye”);
}

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

  • 本文作者: 帐前卒
  • 本文链接: http://chillyc.info/2008/2302292/
  • 版权声明: 本博客所有文章除特别声明外,只能复制超链接地址,且必须注明出处!