javascript - 使用 jquery ajax json 发送表单数据

标签 javascript php jquery ajax json

我是 PHP/jquery 新手 我想问一下如何使用 ajax 以 json 格式从表单字段(如姓名、年龄等)发送 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>

最佳答案

这是一个简单的例子

这里是我的test.php,仅供测试

<?php

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

echo json_encode($_POST);

这是我的 index.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>

两个文件放在同一个目录

关于javascript - 使用 jquery ajax json 发送表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30680562/

相关文章:

javascript - $ionicPopup : e. PreventDefault() 被忽略

javascript - 谷歌地图 : Uncaught ReferenceError: google is not defined

jquery - 光滑的旋转木马图像不垂直适合屏幕且不垂直居中

jquery - 返回所有 JSON 值的平均值

javascript - 无法将项目插入空数组

javascript - 将Json数据转换为数组

javascript - res.json 返回无意修改的输入

javascript - 当从android调用带有一些js代码的php文件时,js代码是这种调用的输出

php - Apache 2.4 中删除了所有带下划线的大写 HTTP header

php - 比较PHP中密码的哈希值