使用 jquery ajax json 发送表单数据

2022-08-30 21:42:43

我是PHP / jquery的新手,我想问一下如何从表单字段(名称,年龄等)以json格式使用ajax发送json数据。可悲的是,我找不到任何相关信息,甚至可以动态地做到这一点?谷歌搜索只会给出答案,比如手动建立数据。如:、、等。name: X Yage: 32

有没有办法做到这一点?

感谢您的帮助!

编辑:

<form action="test.php" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input type="submit">
</form>

答案 1

这是一个简单的

这是我的测试.php仅用于测试

<?php

// this is just a test
//send back to the ajax request the request

echo json_encode($_POST);

这是我的索引.html

<!DOCTYPE html>
<html>

<head>

</head>
<body>

<form id="form" action="" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input id="submit" type="button" name="submit" value="submit">
</form>




<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        // click on button submit
        $("#submit").on('click', function(){
            // send ajax
            $.ajax({
                url: 'test.php', // url where to submit the request
                type : "POST", // type of action POST || GET
                dataType : 'json', // data type
                data : $("#form").serialize(), // post data || get data
                success : function(result) {
                    // you can see the result from the console
                    // tab of the developer tools
                    console.log(result);
                },
                error: function(xhr, resp, text) {
                    console.log(xhr, resp, text);
                }
            })
        });
    });

</script>
</body>
</html>

两个文件都位于同一目录中


答案 2

这里接受的答案确实从表单中制作了一个json,但json内容实际上是一个带有url编码内容的字符串。

要制作更逼真的 json POST,请使用从序列化表单数据到 JSON 的一些解决方案来生成函数并添加到 jQuery ajax 调用参数。formToJsoncontentType: 'application/json;charset=UTF-8'

$.ajax({
    url: 'test.php',
    type: "POST",
    dataType: 'json',
    data: formToJson($("form")),
    contentType: 'application/json;charset=UTF-8',
    ...
})