jquery - 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>
解决方案
推荐阅读
- node.js - 如何设置要在所有 ejs 文件中使用的局部变量
- kotlin - 在 Reified 之后我们还需要 Class(或 KClass)吗?
- prolog - 找到一个数的所有自然除数(使用 Prolog)
- php - 120 if语句是否有任何快捷方式用于在php中使用空白文件输入类型更新数据库?
- python - 如何在redis python中将具有值的字典存储为列表
- c# - 使用asp mvc连接生物识别zkemkeeper?
- python - pandas:如何将数据框的所有数字列转换为对数
- process - 在无限超时后使用接收挂起 Erlang 进程
- ios - 如何在不阻塞用户交互的情况下执行 tableView.reloadData()
- postgresql - pgmodeler 是否仅用于 PostgreSQL?