Javascript 使用 jquery ajax json 发送表单数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30680562/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:35:15  来源:igfitidea点击:

Send form data with jquery ajax json

javascriptphpjqueryajaxjson

提问by user1888798

I'm new in PHP/jquery I would like to ask how to send json data from a form field like (name, age, etc) with ajax in a json format. Sadly I can't found any relevant information about this it's even possible to do it dynamically? Google searches only gives back answers like build up the data manually. like: name: X Y, age: 32, and so on.

我是 PHP/jquery 新手我想问一下如何使用 ajax 以 json 格式从表单字段(如(姓名、年龄等))发送 json 数据。可悲的是,我找不到任何有关此的相关信息,甚至可以动态执行此操作吗?谷歌搜索只返回答案,比如手动建立数据。像:name: X Y,,age: 32等等。

Is there anyway to do that?

有没有办法做到这一点?

Thanks for the help!

谢谢您的帮助!

Edit:

编辑:

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

回答by Oli Soproni B.

here is a simple one

这是一个简单的

here is my test.php for testing only

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

<?php

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

echo json_encode($_POST);

here is my index.html

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

Both file are place in the same directory

两个文件都放在同一个目录下

回答by Roman Susi

The accepted answer here indeed makes a json from a form, but the json contents is really a string with url-encoded contents.

此处接受的答案确实从表单中生成了 json,但 json 内容实际上是带有 url 编码内容的字符串。

To make a more realistic json POST, use some solution from Serialize form data to JSONto make formToJsonfunction and add contentType: 'application/json;charset=UTF-8'to the jQuery ajax call parameters.

为了制作更逼真的 json POST,使用一些从Serialize form data to JSONto make formToJsonfunction 并添加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',
    ...
})

回答by Beginner

You can use serialize()like this:

你可以这样使用serialize()

$.ajax({
  cache: false,
  url: 'test.php',
  data: $('form').serialize(),
  datatype: 'json',
  success: function(data) {

  }
});

回答by Frank B

Sending data from formfields back to the server (php) is usualy done by the POST method which can be found back in the superglobal array $_POST inside PHP. There is no need to transform it to JSON before you send it to the server. Little example:

将数据从表单域发送回服务器 (php) 通常是通过 POST 方法完成的,该方法可以在 PHP 内部的超全局数组 $_POST 中找到。在将其发送到服务器之前,无需将其转换为 JSON。小例子:

<?php

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    echo '<pre>';
    print_r($_POST);
}
?>
<form action="" method="post">
<input type="text" name="email" value="[email protected]" />
<button type="submit">Send!</button>

With AJAX you are able to do exactly the same thing, only without page refresh.

使用 AJAX,您可以做完全相同的事情,而无需刷新页面。