如何使用 html 表单数据发送 JSON 对象 [英] How to send a JSON object using html form data
问题描述
所以我有这个 HTML 表单:
So I've got this HTML form:
<html>
<head><title>test</title></head>
<body>
<form action="myurl" method="POST" name="myForm">
<p><label for="first_name">First Name:</label>
<input type="text" name="first_name" id="fname"></p>
<p><label for="last_name">Last Name:</label>
<input type="text" name="last_name" id="lname"></p>
<input value="Submit" type="submit" onclick="submitform()">
</form>
</body>
</html>
当用户点击提交时,将表单数据作为 JSON 对象发送到我的服务器的最简单方法是什么?
Which would be the easiest way to send this form's data as a JSON object to my server when a user clicks on submit?
更新:我已经走了这么远,但似乎没有用:
UPDATE: I've gone as far as this but it doesn't seem to work:
<script type="text/javascript">
function submitform(){
alert("Sending Json");
var xhr = new XMLHttpRequest();
xhr.open(form.method, form.action, true);
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
var j = {
"first_name":"binchen",
"last_name":"heris",
};
xhr.send(JSON.stringify(j));
我做错了什么?
推荐答案
以数组的形式获取完整的表单数据并进行 json 字符串化.
Get complete form data as array and json stringify it.
var formData = JSON.stringify($("#myForm").serializeArray());
你可以稍后在ajax中使用它.或者,如果您没有使用 ajax;把它放在隐藏的 textarea 中并传递给服务器.如果此数据通过普通表单数据作为 json 字符串传递,则您必须使用 json_decode 对其进行解码.然后您将获得数组中的所有数据.
You can use it later in ajax. Or if you are not using ajax; put it in hidden textarea and pass to server. If this data is passed as json string via normal form data then you have to decode it using json_decode. You'll then get all data in an array.
$.ajax({
type: "POST",
url: "serverUrl",
data: formData,
success: function(){},
dataType: "json",
contentType : "application/json"
});
这篇关于如何使用 html 表单数据发送 JSON 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!