【发布时间】:2016-06-26 11:33:48
【问题描述】:
我是 JQuery 的初学者,我正在尝试做一件非常简单的事情:获取一个 html 表单,将其转换为 JSON,将其发送到我的 API 并显示结果。
我阅读了多篇关于将表单和数组序列化为 JSON 的 SO 帖子,但我无法让它工作(我要么收到 400 - Bad Request 响应,因为我的 JSON 格式不正确或由于某种原因出现 415 状态)。
这是 Html 表单:
<form id="imageUploadForm">
<fieldset>
<legend>Upload new image</legend>
<p>
<label for="imageUrl">Image URL:</label>
<input id="imageUrl" type="text" name="imageUrl" />
</p>
<p>
<label for="tag">Tag:</label>
<input id="tag" type="text" name="tag" />
</p>
<p>
<input id="uploadButton" type="button" value="Submit" />
</p>
</fieldset>
</form>
<div id="uploadResponse"></div>
以及处理请求的脚本:
$(document).ready(function() {
//Stops the submit request
$("#imageUploadForm").submit(function(e) {
e.preventDefault();
});
//checks for the button click event
$("#uploadButton").click(function(e) {
//get the form data and then serialize that
var json = JSON.parse(JSON.stringify(jQuery('#imageUploadForm').serializeArray()));
$.ajax({
type: "POST",
url: "<url>",
data: json,
crossDomain: true,
dataType: "text/plain",
//if received a response from the server
success: function(response) {
$("#uploadResponse").append(response);
},
});
});
});
有人能指出我正确的方向吗?目标是将以下 JSON 发送到 api:
{
"imageUrl" : "...",
"tag" : "..."
}
【问题讨论】:
-
试试
var json=$('#imageUploadForm').serialize() -
也许这会有所帮助
contentType: "application/json; charset=utf-8" -
尝试使用这个答案的解决方案 - stackoverflow.com/a/1186309/6014444
标签: javascript jquery html json