首页 > 解决方案 > JQuery AJAX如何将HTML表单数据转换为JSON

问题描述

我正在编写教程,并希望将数据发布到 api。我正在查看这个 swagger 文档http://petstore.swagger.io/#/pet/addPet我想获取 HTML 表单数据并将其发布到 API。API 要求将 JSON 制作成如下格式:

{
  "id": 1104,
  "category": {
     "id": 0,
     "name": "string"
},
"name": "doggie",
"photoUrls": [
    "string"
],
"tags": [
  {
    "id": 0,
    "name": "string"
  }
],
"status": "available"
}

我将如何配置表单数据以满足这些规范?这是我目前拥有的。

<!DOCTYPE html>
<html>

<head>

</head>
<body>

   <form id="form" action="" method="post">
    Id: <input type="text" name="id"><br>
    Category Id: <input type="text" name="categoryId"><br>
    Category Name: <input type="text" name="categoryName"><br>
    PhotoURLs: <input type="text" name="photoUrls"><br>
    TagsId: <input type="text" name="tagsId"><br>
    TagsName: <input type="text" name="tagsName"><br>
    Status: <input type="text" name="status"><br>
    <input id="submit" type="button" name="submit" value="submit">
</form>




<script
    src="https://code.jquery.com/jquery-3.3.1.min.js"
    integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
    crossorigin="anonymous"></script>

<script>

    $(document).ready(function(){
        // click on button submit
        $("#submit").on('click', function(){

       var formData = {
            "id": $('input[name=id]').val(),
            "category": {
                "id": $('input[name=categoryId]').val(),
                "name": $('input[name=categoryName]').val()
            },
            "name": $('input[name=name]').val(),
            "photoUrls": [
                $('input[name=photoUrls]').val()
            ],
            "tags": [
                {
                    "id": $('input[name=tagsId]').val(),
                    "name": $('input[name=tagsName]').val()
                }
            ],
            "status": $('input[name=status]').val()
        };

           // send ajax
           $.ajax({
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            },
            url: 'https://petstore.swagger.io/v2/pet', // url where to submit the request
            type : "POST", // type of action POST || GET
            dataType : 'json', // data type
            data : JSON.stringify(formData), // 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>

标签: jqueryajaxformsapipost

解决方案


推荐阅读