簡體   English   中英

JQuery 以正確的格式將 html 格式轉換為 JSON

[英]JQuery convert html form to JSON in a correct format

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM