簡體   English   中英

帶有XMLHttpRequest的open方法的javascript:使用post及其參數

[英]javascript with XMLHttpRequest's open method: using post and its parameters

理想情況下,我的網站的用戶將在大約一個小時的時間內將幾百個帖子發送到db服務器(基本上是在線實驗)。 該實驗是用js實現的,因此我嘗試使用XMLHttpRequest對象發布腳本收集的數據。

我不確定的是如何使用POST參數。 我想為$ _POST變量設置大約8個不同的鍵/值對,以便.php頁可以在將其發送到數據庫服務器之前對其進行處理。 我對從服務器本身檢索任何信息不感興趣,僅發送信息(這就是原因,並且我不確定這是否正確,我將readyState的條件設置為“ 1” /打開)。

這是我目前正在使用的腳本:

function postData(dataList) {

 var xmlhttp = new XMLHttpRequest();
 var processingUrl = "process_exercise_data.php";
 var POSTBody = "";
 POSTBody+="block_type="+encodeURIComponent(dataList[0]);
 POSTBody+="&block_number="+encodeURIComponent(dataList[1]);
 POSTBody+="&trial_type="+encodeURIComponent(dataList[2]);
 POSTBody+="&trial_number="+encodeURIComponent(dataList[3]);
 POSTBody+="&input_value="+encodeURIComponent(dataList[4]);
 POSTBody+="&output_value="+encodeURIComponent(dataList[5]);
 POSTBody+="&prediction_value="+encodeURIComponent(dataList[6]);
 POSTBody+="&error="+encodeURIComponent(dataList[7]);


 xmlhttp.open("POST",processingUrl,true);
 if (xmlhttp.readyState==4) {
  xmlhttp.send(POSTBody);
 }

}

主要目標是使用POST將鍵/值對發送到.php頁面,同時保留在當前頁面上 (簡單的AJAX請求,如果我沒記錯的話)。 任何意見或建議都非常感謝!

記住,我要做的就是讓用戶在特定條件下(在此功能范圍之外)以某種方式行事,以調用該功能並將該數據發布到服務器。 不需要服務器響應文本。

編輯:

現在我的問題是:我仍然可以在正在處理的php頁面中訪問$ _POST數組嗎? 這是一個例子:

$block_type = $_POST['block.type'];

您不想設置請求標頭。 您要發送的是請求正文 而且身體應該像

'block_type='+encodeURIComponent(dataList[0])+'&block_number='+encodeURIComponent(dataList[1])

等。猜猜你有這個主意。 正文是傳遞給XMLHTTPRequest對象的send()方法的內容。

考慮使用jQuery,它將使您的任務變得如此輕松。 使用jQuery.post方法,您只需要提供data哈希即可,而不必擔心序列化,正確的轉義或readyState

您必須先調用send才能更改readyState

更換

xmlhttp.open("POST",processingUrl,true);
if (xmlhttp.readyState=4) {
  xmlhttp.send(POSTBody);
}

xmlhttp.open("POST", processingUrl, false);
xmlhttp.send(POSTBody);

如果要處理響應,請添加define xmlhttp.onreadystatechange

xmlhttp.open("POST", processingUrl, false);
xmlhttp.onreadystatechange = function () {
  if (this.readyState === 4) {
    // handle response
  }
};
xmlhttp.send(POSTBody);

編輯:我還要提及=不是JavaScript相等運算符,它是賦值運算符。 ===用於相等性檢查,將==用於類型轉換相等性檢查。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM