Ajax中send方法參數的使用
一般情況下,使用Ajax提交的參數多是些簡單的字符串,可以直接使用GET方法將要提交的參數寫到open方法的url參數中,此時send方法的參數為null。
例如 :
var url = "login.jsp?user=XXX&pwd=XXX";
xmlHttpRequest.open("GET",url,true);
xmlHttpRequset.send(null);
此外,也可以使用send方法傳遞參數。使用send方法傳遞參數使用的是POST方法,需要設定Content-Type頭信息,模擬HTTP POST方法發送一個表單,這樣服務器才會知道如何處理上傳的內容。參數的提交格式和GET方法中url的寫法一樣。設置頭信息前必須先調用open方法。
例如:
xmlHttpRequest.open("POST","login.jsp",true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
xmlHttpRequest.send("user="+username+"&pwd="+password);
需要注意的是根據提交方式的不同,兩種提交方式分別調用后台的doGet方法和doPost方法。