讓我解釋一下爲什麼我需要這樣做!是否可以通過POST使用javascript多次發送一個變量?
我需要請求發送到另一臺服務器,它的格式是這樣的:
http://www.test.ccom/process?item=1AAA&item=2BBB&item=3CCC
此URL將新增3個不同的項目(每一個)的結果頁面,如下所示:
Item = 1AAA Count=1
Item = 2BBB Count=1
Item = 3CCC Count=1
如果我想補充一點,3只是一個項目,我應該用這樣的:
http://www.test.ccom/process?item=1AAA&item=1AAA&item=1AAA
而結果頁面將是這樣的:
Item = 1AAA Count=3
我的問題是我不能使用GET方法(因爲我們要添加100個項目超過發送我的請求,它會導致「請求-URI太大「錯誤)
我使用兩種不同的方法通過POST發送此請求,但沒有成功。
首先,我用這個功能:
function post_by_form(path, params) {
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", path);
form.setAttribute("style", "display: none")
for(var key in params) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", "item");
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
document.body.appendChild(form);
form.submit();
}
它的工作原理,當我用不同的變量名稱(NAME =「項」 +鍵)進行測試,但是當我使用一個變量名,這是行不通的所有的投入。
然後我用這個功能通過AJAX發送POST請求:
function post_by_ajax(path, params_arr){
var http = new XMLHttpRequest();
var url = path;
var params = "";
for(var key in params_arr) {
if (params != "")
params += "&item="+params_arr[key];
else
params += "item="+params_arr[key];
}
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
}
同樣的結果,無論這個方法會返回只有一個數量只是一個項目(最後一個)......雖然我們可以提交一個帶有很多輸入字段的表單,並且都使用相同的名稱,爲什麼我不能用這些方法來完成它?我在邏輯上有什麼問題嗎?!有人能幫幫我嗎?!
'$ .post(url,{},function(response){});' - 爲什麼不呢? – devdRew 2012-01-05 21:15:25
@devdRew:發送是可能的,讓它在服務器端是棘手的! ;) – Monica 2012-01-05 22:30:54