代码改变世界

Javascript端ajax的Post和Get请求

2012-08-14 18:00  C#与.NET探索者  阅读(425)  评论(0编辑  收藏  举报

JS中Ajax异步传值

<script type="text/javasccript">

var xmlHttp;

function createXmlRequest()

{

//IE浏览器

if(window.ActiveXObject)

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

//非IE浏览器

else if(window.XMLHttpRequest)

xmlHttp=new XMLHttpRequest();

}

 

function Startreadystate()

{

CreateXmlRequest();

xmlHttp.onreadystatechange=handlerStateChange;

xmlHttp.open("GET","Default.aspx?Name="+escape(document.getElementByIdx_x_x("txtName").value),true);

xmlHttp.send(null);

}

 

function handlerStateChange()

{

if(xmlHttp.readystate=="4" && xmlHttp.status=="200")

{

if(xmlHttp.responseText=="zhangsan")

{

document.getElementByIdx_x_x("label1").innerText=xmlHttp.responseText;

}

}

}

</script>

注:

GET:

//ReturnMethod为成功返回后调用的方法

xmlHttp.onreadystatechange=ReturnMethod;

xmlHttp.open("GET","Default.aspx?Name="+escape(name),true);

xmlHttp.send(null);

 

POST:

var para="Name="+escape(name);

xmlHttp.onreadystatechange=ReturnMethod;

xmlHttp.open("POST","Default.aspx",true);

//用POST异步一定要加下面这个语句

xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");

xmlHttp.send(para);

 

在Default.aspx.cs页面中

如果用POST异步传值,要想在JS中用responseText接收到值,

必须用Response.Clear()先清楚

Response.Write("zhangsan");

然后用Response.End()从内存中输出;

用GET异步传世也可不用Response.Clear();