use*_*798 13 javascript php ajax jquery json
我是PHP/jquery的新手我想询问如何使用json格式的ajax从表单字段(名称,年龄等)发送json数据.可悲的是,我找不到任何相关的信息,甚至可以动态地做到这一点?Google搜索仅返回手动构建数据等答案.喜欢:name: X Y,age: 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>
Run Code Online (Sandbox Code Playgroud)
    Oli*_* B. 19
这是一个简单的
这是我的test.php仅用于测试
<?php
// this is just a test
//send back to the ajax request the request
echo json_encode($_POST);
Run Code Online (Sandbox Code Playgroud)
这是我的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>
Run Code Online (Sandbox Code Playgroud)
两个文件都放在同一目录中
此处接受的答案的确是从表单生成json,但是json的内容实际上是带有url编码内容的字符串。
要进行更现实的JSON POST,请使用从序列化表单数据到JSON的某种解决方案来实现formToJson功能,并将其添加contentType: 'application/json;charset=UTF-8'到jQuery ajax调用参数中。
$.ajax({
    url: 'test.php',
    type: "POST",
    dataType: 'json',
    data: formToJson($("form")),
    contentType: 'application/json;charset=UTF-8',
    ...
})
Run Code Online (Sandbox Code Playgroud)
        |   归档时间:  |  
           
  |  
        
|   查看次数:  |  
           89553 次  |  
        
|   最近记录:  |