javascript - JQuery 将 html 形式转换为正确格式的 JSON

标签 javascript jquery html json

我是 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/

相关文章:

javascript - 使用 IP 地址而不是域名来抓取网络服务器的屏幕

jquery - 那真是怪了。仅显示某些网址的iframe fancybox内容?

javascript - 访问 JSON 中的属性(对象)

javascript - Typescript 指南给出 "Duplicate function implementation"警告

javascript - 滚动 "stack"个 DOM 对象

html - 单选按钮图像不允许选择值

html - 如何在 div 的中心对齐具有特定宽度的文本?

javascript - 如何在 Javascript DOM 更新后触发 CSS 布局重新计算?

javascript - 转换阴影

javascript - 获取多个字符串之间的字符串,即 HTML 标签