我是 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" : "..."
}
最佳答案
您可以检查以下代码和 fiddle 链接吗,
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$("#imageUploadForm").submit(function(e) {
e.preventDefault();
});
$('#uploadButton').click(function() {
var jsonText = JSON.stringify($('form').serializeObject());
$('#result').text(JSON.stringify($('form').serializeObject()));
$.ajax({
type: "POST",
url: "<url>",
data: jsonText,
crossDomain: true,
dataType: "text/plain",
//if received a response from the server
success: function(response) {
$("#uploadResponse").append(response);
},
});
});
});
http://jsfiddle.net/sxGtM/7142/
希望对您有帮助。
关于javascript - JQuery 将 html 形式转换为正确格式的 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35936553/