将json表单数据发送到服务器

时间:2014-08-12 12:40:09

标签: javascript html json forms

我正在尝试从表单中获取数据并将其发送到远程服务器:

代码是:

<html>

    <head>
        <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    </head>

    <body>

<h2>Create Sensor</h2>

<form id="form">
<form enctype='application/json'>
  <input name='version' value='1.0.1'>
  <input name='sensors[0][sensor]' value=''>
  <input name='sensors[0][output][0][name]' value=''>
  <input name='sensors[0][output][0][type]' value=''>
  <br>
            <input id="input" type="submit" name="submit" value="Create Sensor" />
</form>
        <script>
            $.ajaxSetup({
                contentType: "application/json; charset=utf-8",
                dataType: "json"
            });

            $(document).ready(function() {
                $('#input').click(function() {
                    var send = $("#form");
                    $.ajax({
                        url: "http://posttestserver.com/post.php",

                        type: "POST",
                        data: send,
                        success: function (sreg, status, jqXHR) {
                        alert(JSON.stringify(sreg));
                            },

                            error: function (jqXHR, status) {
                                alert(JSON.stringify(jqXHR));
                            }
                    });
                    return false;
                });
            });
        </script>
    </body>

</html>

但是JSON没有正确形成,因为我正在通过警报返回。有人可以帮帮我吗?我不擅长编码只是想学习

这是预期的JSON:

{
    "version": "1.0.1",
    "sensors": [
        {
            "sensor": "",
            "output": [
                {
                    "name": "",
                     "type": ""
                }
            ]
        }
    ]
}

另一个问题是:是否有任何在线平台可以通过输入这样的JSON表单来获得预期的JSON?请帮帮我

1 个答案:

答案 0 :(得分:0)

你的脚本:post.php应该使用表单数据并返回一个JSON对象。

要将数组数据发送到您应该使用的脚本。

var send = $("#form").serializeArray();

您可以在此处轻松检查您的JSON是否有效:

http://jsoneditoronline.com/

相关问题