JQuery 以正确的格式将 html 表单转换为 JSON

JQuery convert html form to JSON in a correct format

本文关键字:表单 html 转换 JSON 格式 JQuery      更新时间:2023-09-26

我是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" : "..."
}

你能检查下面的代码和小提琴链接吗,

$.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/

希望对您有所帮助。

您不必解析字符串化的 JSON,否则会发送 JS 对象。您必须发送一个字符串,呈现一个 JSON。

var json = JSON.stringify(jQuery('#imageUploadForm').serializeArray());

尝试将内容类型更改为 contentType: "application/json; charset=utf-8", 以及您的 API 是否返回 json 集dataType: "json" .

您的控制台报告是什么(如果有的话)?

只需使用var json=$('#imageUploadForm').serialize()

根据您有问题的表单,您不需要serializeArray和更改内容类型contentType:"application/json; charset=utf-8",

检查此 SO 链接

    var imagedataUrl = $("#imageUrl").val();
    var tagdataUrl = $("#tag").val();
    $.ajax({
    type: "POST",
    url: "<url>",
     dataType: "json",
    data: { imageUrl: imagedataUrl  , tag: tagdataUrl },
    contentType: "application/json; charset=utf-8;",
    crossDomain: true,

    //if received a response from the server
    success: function(response) {
            $("#uploadResponse").append(response);
    },
    });

您应该提及发送到服务器的内容类型

varContentType="application/json; charset=utf-8";
$.ajax({
    type: varType, //GET or POST or PUT or DELETE verb
    url: varUrl, // Location of the service 
    data: varData, //Data sent to server
    contentType: varContentType, // content type sent to server
    dataType: varDataType, //Expected data format from server
    processData: false,
    crossDomain: true,
});