ajax xmlhttprequest使用post傳引數並向後臺獲取資料
ajax xmlhttprequest向後臺傳資料有兩種方式,一種是直接在地址URL後面加入引數,後臺用Request.QueryString來獲取,另外一種是採用POST來傳,send方法傳送引數對,比如send("a=3&b=4"),後臺用Request.Form[“a”]來獲取3,同理Request.Form["b"]獲取4
前臺程式碼:
<%@ Page Title="主頁" Language="C#" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="ajax測試二._Default" %>
<html>
<head>
<script type="text/javascript">
function getHttpObj() {
var httpobj = null;
try {
httpobj = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpobj = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e1) {
httpobj = new XMLHttpRequest();
}
}
return httpobj;
}
function cs() {
var obj = getHttpObj();
var sel1 = document.getElementById('cs1');
//obj.open("get", "default.aspx?id=" + cs1.value, true); //記得小寫,親,並且default.aspx不區分大小寫,這裡在IE存在快取問題,使用下面的可以解決
obj.open("post", "default.aspx?id=" + cs1.value,true);//ajax非同步在使用GET方式的時候在IE下面存在快取,不會向後臺請求,不過POST不存在快取問題
//obj.send(); //記得小寫,親,不傳引數可以直接這樣寫
obj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");//不加上這句,那麼後臺Request.Form獲取不到引數a,b的數值
obj.send("a=3&b=4");
obj.onreadystatechange = function () {//此處為回撥函式
if (obj.readyState == 4 && obj.status == 200) {
alert(obj.responseText);
}
};
}
</script>
</head>
<body>
<select id="cs1" onchange="cs();">
<option value="1">江西省</option>
<option value="2">福建省</option>
</select>
</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測試二
{
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"];
Response.Write("id:"+Request.QueryString["id"]+",a:"+Request.Form["a"]+",b:"+Request.Form["b"]);
Response.End();
}
}
}
}
程式在IE8,filefox,chorme下測試通過