| .NET使用ajax最基本代码实例 |
| 来源:
发布时间:2008-01-19 发布人:
浏览:
人次
字体:
[大
中
小]
|
|
记录一段AJAX的基本写法,代码加注释,很多人认为它神秘,其实看了就明白了
这里用.NET的ASPX做返回处理的服务端
JS代码,调用方法
<script type ="text/javascript">
var request = false;
 try ...{
request = new XMLHttpRequest();//非微软浏览器
 } catch (trymicrosoft) ...{
 try ...{
request = new ActiveXObject("Msxml2.XMLHTTP");//微软IE
 } catch (othermicrosoft) ...{
 try ...{
request = new ActiveXObject("Microsoft.XMLHTTP");//微软其他
 } catch (failed) ...{
request = false;
}
}
}
if (!request)//老式浏览器不支持XMLHttpRequest对象的
alert("Error initializing XMLHttpRequest!");
 function getCustomerInfo() ...{
var phone = document.getElementById("Text1").value;//获取表单上Text摸值
var url = "http://localhost:14379/WebHtmlPartDynamic/Default2.aspx?phone="+escape(phone);//请求的网页
request.open("GET", url, true);//建立请求:GET方式,地址,TRUE为异步调用
request.onreadystatechange = updatePage;//服务器处理完毕调用哪个方法
request.send(null);//发送请求(一般不发送安全信息和XML为NULL)
}
 function updatePage() ...{
if(request.readyState ==4)//判断HTTP请求的就绪状态,这里4是最后一状态
if (request.status == 200)//请求正常的状态码为200(返回错误连接的404类似的一种表示)
 ...{
var dh = request.responseText;
alert(dh);
}
else if (request.status == 404)//以下为错误检查
alert("Request URL does not exist")
else
alert("Error: status code is " + request.status);
}
</script>
HTML代码 如何调用
<body>
<form id="form1" runat="server">
<div>
<input id="Text1" type="text" />
<input id="Submit1" type="submit" value="submit" onclick = "getCustomerInfo()" /></div>
</form>
</body>
ASPX里写的,做为响应AJAX请求的处理部分
protected void Page_Load(object sender, EventArgs e)
 ...{
if (!IsPostBack)
 ...{
string str = Request.QueryString["phone"];
Response.Write(str);
Response.Flush();
Response.End();
}
}
| |
| |
|
|
|
|
| §最新评论:(评论内容只代表网友观点,与本站立场无关!) | |
|
|
|
|
| 注意:请勿在本站发布政治话题、色情及违反法律的内容。 |
IT知道网 声明:刊登此文章是为了传递更多信息,文章内容仅供参考,转载请注明出处。 |