[英]How to pass form data using POST method and JS submit()?
如何使用POST方法和JS submit()傳遞表單數據?
我不想使用AJAX。
我可以通過使用JS和GET方法實現這一點,但我現在的目標是使用JS(可能使用submit())和POST方法。
請舉一個簡單的工作示例。
謝謝!
編輯:對不起,我會更具體。 這是一個簡單的代碼:
<form name=\"myform\" action=\"\">
Search: <input type='text' name='query' />
<a href=\"javascript: submitform()\">Search</a>
</form>
<script type=\"text/javascript\">
function submitform() { document.myform.submit(); }
</script>
當我在輸入字段中插入“word”並按Search時,URL變為“../index.php?query=word”,這意味着表單數據像GET方法一樣傳遞。
我的目標是從URL中刪除任何表單數據並像POST方法一樣傳遞它。
編輯:哦..我剛剛在URL中添加了method = post和沒有表單數據:)
只需要一個表格並提交即可。
form = document.forms[0] //assuming only form.
form.submit();
在表單上指定method
屬性。
<form name="myform" action="" method="POST">
它將導致表單作為POST提交。
將表單的method
屬性設置為POST:
<form method="post">
然后使用<formelement>.submit()
通過JavaScript提交表單
如前所述,您可以使用表單。 我發現有一個函數可以動態創建一個表單並提交它 - 這樣你就不需要用表單來混淆你的標記,直到你的JS需要它們為止。
function PostObjectToUri(uri, obj) {
"use strict";
var json, form, input;
json = JSON.stringify(obj);
form = document.createElement("form");
form.method = "post";
form.action = uri;
input = document.createElement("input");
input.setAttribute("name", "json");
input.setAttribute("value", json);
form.appendChild(input);
document.body.appendChild(form);
form.submit();
};
顯然,示例JSON將對象序列化為字符串並將其設置在單個輸入上,但您可以根據需要調整它。
編輯 :我不確定你是否需要在提交之前附加到DOM - 有人可以澄清嗎?
jQuery AJAX帖子是最好的方法。 見下面的示例代碼。
e.preventDefault();
$.ajax({
type: 'post',
url: 'data.php',
data: $('form').serialize(),
success: function(response) {
$('#DisplayDiv').html(response);
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.