[英]Submit form data to servlet and retrieve answer without page reloading?
在網頁上,我想將帶有POST請求的表單數據提交給servlet,接收答案並根據結果進行處理。 該頁面不得重新加載。 不幸的是,我對這種事情(HTML和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.