【问题标题】:JQuery convert html form to JSON in a correct formatJQuery 以正确的格式将 html 表单转换为 JSON
【发布时间】: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


【解决方案1】:

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

$.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 序列化表单这样简单的事情不应该需要那么多样板代码
【解决方案2】:

你不必解析字符串化的 JSON,否则你发送一个 JS 对象。您必须发送一个表示 JSON 的字符串。

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

【讨论】:

    【解决方案3】:

    尝试将内容类型更改为contentType: "application/json; charset=utf-8",,如果您的api返回json集dataType: "json"

    您的控制台报告什么?

    【讨论】:

      【解决方案4】:

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

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

      检查这个SO link

      【讨论】:

      • 我尝试了 console.log(json) ,它产生了 url 编码的内容:imageUrl=...&tag=... 从而导致错误请求
      【解决方案5】:
          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);
          },
      
          });
      

      【讨论】:

      • 您的代码生成以下有效负载:imageUrl=...&tag=... 它不会将这些数据解释为 JSON
      • 使用数据:JSON.stringify(object)
      • 您能提供一个工作示例吗?这只会导致 415
      【解决方案6】:

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

      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,
      });
      

      【讨论】:

        猜你喜欢
        • 2019-03-18
        • 1970-01-01
        • 1970-01-01
        • 2018-10-08
        • 1970-01-01
        • 2015-09-02
        • 2013-07-02
        • 2020-05-09
        相关资源
        最近更新 更多