簡體   English   中英

將表單數據提交到servlet並檢索答案而無需重新加載頁面?

[英]Submit form data to servlet and retrieve answer without page reloading?

在網頁上,我想將帶有POST請求的表單數據提交給servlet,接收答案並根據結果進行處理。 該頁面不得重新加載。 不幸的是,我對這種事情(HTML和JavaScript)不是很有經驗。

目前,我已成功獲得兩個失敗的結果:

  1. 發送POST請求(由Servlet正確處理),然后頁面重新加載並顯示純XML結果
  2. 或從不發送POST請求,JavaScript函數進行了一些處理,但基本上沒有結果。

我從以下頁面獲得了以這種方式進行操作的想法: https : //www.w3schools.com/xml/xml_http.asp

特別:

XMLHttpRequest對象是開發人員的夢想,因為您可以:
更新網頁而無需重新加載頁面

目前,我沒有這樣做。


我有這樣的HTML表單:

<form id="editform" 
    action="myAction" 
    method="post" 
    onSubmit="return submitForm(this);">

  ....

  <input type="hidden" name="operation" value="doSomething" />
  <input type="image" src="images/button.png" />
</form>

在頁面的head我有一個像這樣的JavaScript:

function submitForm(oFormElement)
{
  var xmlHttpRequest = new XMLHttpRequest();
  xmlHttpRequest.open (oFormElement.method, oFormElement.action, true);
  xmlHttpRequest.onload = function()
  { 
    if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) 
    {
      alert (xmlHttpRequest.responseXml);
    }
    else
    {
      alert ("Failed!");
    }
  };
  xmlHttpRequest.send (new FormData (oFormElement));
  return false;
}

如果JavaScript返回false那么我在瀏覽器Web開發人員控制台中看不到任何POST請求,並且Servlet永遠不會收到任何請求。 警報框打印未定義 (情況2)。

如果JavaScript返回true ,則確實發送了POST請求,並返回了正確的結果,但是頁面已重新加載(情況1)。

在肯定的if子句中,我要處理結果XML並相應地設置HTML元素。

您應該使用jQuery $ .ajax

例:

$.ajax({
url: "myUrl", // url to make request
type: "POST", // method of request
data: {key: "value"}, // Here comes your data
success: function(response){ // If request is made successful
    //  Here you can handle response from your request
    console.log(response)
},
error: function(xhr){// If request has faced issue
    console.log(xhr.responseText)
}});

必須使用xmlHttpRequest.responseXML代替xmlHttpRequest.responseXml 似乎oFormElement.action也沒有像我希望的那樣拾取我的<input>元素。

暫無
暫無

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

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