刚刚接触Ajax,一个小问题,纠结了一天,终于解决了。
前端代码:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Ajax_text.aspx.cs" Inherits="Ajax_text" %>
<!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">
<title></title>
<script type="text/javascript">
var xmlhttp = null;
function Validation() {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Micosoft.XMLHTTP");
}
var name = document.getElementById("name1");
xmlhttp.open("GET", "Ajax_text.aspx?name=" +name.value,true);
xmlhttp.onreadystatechange = onMessageBack;
xmlhttp.send(null);
}
function onMessageBack() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var str = xmlhttp.responseText;
if (str == "OK") {
document.getElementById("div1").innerHTML = document.getElementById("name1").value + "你好";
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input type="text" id="name1">
<input type="button" value="haha" οnclick="Validation()">
<div id="div1"></div>
</div>
</form>
</body>
</html>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Ajax_text : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["name"] != null)
{
string name = Request.QueryString["name"].ToString();
Response.Write("OK");
Response.End();
}
}
}
问题是:
在不加Response.End(); 时,前端显示的带有html内容的。这不是我想要的,我只要 OK 就行,
问题原因在于自己对于responseText的不理解。其实responseTex本身就是返回整个页面,而只要
用Response.End()阻止返回整个页面就行了。