如何使用html表单数据发送JSON对象 [英] How to send a JSON object using html form data

查看:149
本文介绍了如何使用html表单数据发送JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这个HTML表单:

 < html> 
< head>< title> test< / title>< / head>
< body>
< form action =myurlmethod =POSTname =myForm>
< p>< label for =first_name>名字:< / label>
< input type =textname =first_nameid =fname>< / p>

< p>< label for =last_name>姓氏:< / label>
< input type =textname =last_nameid =lname>< / p>

< input value =Submittype =submitonclick =submitform()>
< / form>
< / body>
< / html>

当用户将此表单的数据作为JSON对象发送到我的服务器时,这将是最简单的方法点击提交?



更新:
我已经走到尽头,但它似乎不工作:

 < script type =text / javascript> 
函数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));

我做错了什么?

解决方案

以数组形式获取完整的表单数据并对其进行字符串化。

  var formData = JSON。字符串化($( #myForm会)serializeArray()); 

您可以稍后在ajax中使用它。或者如果你不使用ajax;把它放在隐藏的textarea并传递给服务器。如果这些数据是通过普通表单数据作为json字符串传递的,那么您必须使用 json_decode 进行解码。然后你将得到一个数组中的所有数据。

  $。ajax({
type:POST,
url:serverUrl,
data:formData,
success:function(){},
dataType:json,
contentType:application / json
});


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>

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));

What am I doing wrong?

解决方案

Get complete form data as array and json stringify it.

var formData = JSON.stringify($("#myForm").serializeArray());

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆