1.前台代码:
<%@ Page Title="主页" Language="C#" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="ajax测试1._Default" %>
<html>
<head>
<script type="text/javascript">
function getXmlHttpObject() {
var httpobj = null;
try{
httpobj = new ActiveXObject("Microsoft.XMLHTTP");//支持IE
}
catch(e) {
try {
httpobj = new XMLHttpRequest();//非IE内核的都支持,高版本的IE其实也支持这个了,测试IE8支持
}
catch (e) {
httpobj = new ActiveXObject("Msxml2.XMLHTTP");//支持IE
}
}
return httpobj;
}
function cs() {
var obj = document.getElementById('cs1');
var index = obj.selectedIndex;
if (index >= 0) {
var httpobj = getXmlHttpObject();
if (httpobj) {
httpobj.open("GET", "Default.aspx?id="+index, false);//注意此处GET可以大写或者小写,还有一个是此处必须是小写的open,IE是无所谓,但是其它浏览器不支持大写
//Open
httpobj.send(); //此处也必须是小写,IE支持Send,但是其它浏览器不支持Send()
if (httpobj.readyState ==4 && httpobj.status == 200) {
alert(httpobj.responseText);
}
}
}
}
</script>
</head>
<body>
<form id="form1" runat="server" >
<select id="cs1" οnchange="cs();" >
<option value="1" >江西省</option>
<option value="2">福建省</option>
</select>
</form>
</body>
</html>
后台代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ajax测试1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["id"] != null)
{
string id = Request.QueryString["id"];
if (id == "1")
Response.Write("11aa");
else
Response.Write("22aa");
Response.End(); //这句也必须加上,不然网页源代码都会输出去了,汗
}
}
}
}
以上程序经过IE8,Firefox,chrome测试可以正常运行。这里获取的后台数据很简单,只是提供了一个同步获取数据的方式,大家可以举一反三。