主要有两个地方要注意
1. OnClientClick="Change();return false;" 这里注意要加"return false;" ,表示执行完客户端代码后,就不执行服务端单击代码了;否则页面再次刷新,而AJAX传入的值直接被刷掉。
2. Response.End();在服务端返回HTML时,将缓存中的内容返回客户端,停止执行HTML页面,触发HttpApplication.EndRequest事件;否则xmlHttp.responseText中的内容将包括整个页面的内容。
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestWeb._Default" %>
- <!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 id="Head1" runat="server">
- <title>Untitled Page</title>
- <script type="text/javascript">
- var xmlHttp;
- function CreateXMLHttpRequest()
- {
- try
- {
- xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
- }
- catch (e)
- {
- try
- {
- xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
- }
- catch (e2)
- {
- xmlHttp = false;
- }
- }
- if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
- xmlHttp = new XMLHttpRequest();
- }
- }
- function Change()
- {
- CreateXMLHttpRequest();
- var url = "Default.aspx?UserName=myname";
- xmlHttp.open("GET", url, true);
- //xmlHttp.send(null);
- xmlHttp.send();
- xmlHttp.onreadystatechange = handle;
- }
- function handle()
- {
- if (xmlHttp.readyState == 4)
- {
- //var isValid = xmlHttp.responseText;
- var text = document.getElementById('TextBox1');
- text.value = xmlHttp.responseText;
- }
- }
- </script>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <table>
- <tr>
- <asp:TextBox ID="TextBox1" runat="server">shanghai</asp:TextBox></tr>
- <tr><asp:Label ID="Label1" runat="server" Text="origin"></asp:Label></tr>
- <tr><asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="Change();return false;" /></tr>
- </table>
- </div>
- </form>
- </body>
- </html>
- using System;
- using System.Collections;
- using System.Configuration;
- using System.Data;
- using System.Linq;
- using System.Web;
- using System.Web.Security;
- using System.Web.UI;
- using System.Web.UI.HtmlControls;
- using System.Web.UI.WebControls;
- using System.Web.UI.WebControls.WebParts;
- using System.Xml.Linq;
- namespace TestWeb
- {
- public partial class _Default : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- if (null != Request.QueryString["UserName"])
- {
- string str = Request.QueryString["UserName"].ToString();
- Response.Write("welcome "+str);
- Response.End();
- }
- }
- }
- }