首頁  >  文章  >  後端開發  >  無法正確地將表單序列化為 json

無法正確地將表單序列化為 json

WBOY
WBOY轉載
2024-02-14 20:36:10640瀏覽

无法正确地将表单序列化为 json

php小編香蕉為您介紹一個常見問題:無法正確地將表單序列化為json。在開發中,我們經常需要將表單資料以json格式傳遞給後端處理。然而,有時候我們會遇到一些問題,例如提交的資料無法正確轉換成json格式。這可能是由於表單中包含了特殊字元或格式不正確所導致的。在本文中,我們將探討一些常見的原因和解決方案,幫助您解決這個問題,確保表單資料正確地序列化為json。

問題內容

我正在嘗試在golang 中創建一個web 應用程序,允許您將收據的詳細資訊輸入到不同的表單中,然後這些表單輸入被序列化為json 對象。但是,我在序列化表單時遇到了麻煩,因為每當我嘗試「提交」收據時,都會收到錯誤訊息。

這是 main.go

package main

import (
    "encoding/json"
    "html/template"
    "log"
    "net/http"
    "strconv"

    "github.com/gorilla/mux"
)

type item struct {
    shortdescription string `json:"shortdescription"`
    price            string `json:"price"`
}

type receipt struct {
    retailer     string `json:"retailer"`
    purchasedate string `json:"purchasedate"`
    purchasetime string `json:"purchasetime"`
    items        []item `json:"items"`
    total        string `json:"total"`
    receiptid    int    `json:"receiptid"`
}

var receiptidcounter int

var receipts = make(map[int]receipt)

func main() {
    r := mux.newrouter()

    r.handlefunc("/", homehandler).methods("get")
    r.handlefunc("/submit", submithandler).methods("post")
    r.handlefunc("/receipt/{id}", receipthandler).methods("get")

    http.handle("/", r)

    log.fatal(http.listenandserve(":8080", nil))
}

func homehandler(w http.responsewriter, r *http.request) {
    t, err := template.parsefiles("templates/home.html")
    if err != nil {
        log.println(err)
        http.error(w, "internal server error", http.statusinternalservererror)
        return
    }

    err = t.execute(w, nil)
    if err != nil {
        log.println(err)
        http.error(w, "internal server error", http.statusinternalservererror)
    }
}

func submithandler(w http.responsewriter, r *http.request) {
    decoder := json.newdecoder(r.body)

    var receipt receipt
    err := decoder.decode(&receipt)
    if err != nil {
        log.println(err)
        http.error(w, "bad request", http.statusbadrequest)
        return
    }

    receiptidcounter++
    receipt.receiptid = receiptidcounter
    receipts[receipt.receiptid] = receipt

    jsonresponse, err := json.marshal(map[string]int{"receiptid": receipt.receiptid})
    if err != nil {
        log.println(err)
        http.error(w, "internal server error", http.statusinternalservererror)
        return
    }

    w.header().set("content-type", "application/json")
    w.write(jsonresponse)
}

func receipthandler(w http.responsewriter, r *http.request) {
    vars := mux.vars(r)
    id, err := strconv.atoi(vars["id"])
    if err != nil {
        log.println(err)
        http.error(w, "bad request", http.statusbadrequest)
        return
    }

    receipt, exists := receipts[id]
    if !exists {
        http.notfound(w, r)
        return
    }

    t, err := template.parsefiles("templates/receipt.html")
    if err != nil {
        log.println(err)
        http.error(w, "internal server error", http.statusinternalservererror)
        return
    }

    err = t.execute(w, receipt)
    if err != nil {
        log.println(err)
        http.error(w, "internal server error", http.statusinternalservererror)
    }
}

這是我的 home.html,這是我主頁的 html

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>receipt input form</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <h1>receipt input form</h1>
    <form id="receipt-form">
        <label>retailer:</label>
        <input type="text" name="retailer" required><br><br>
        
        <label>purchase date:</label>
        <input type="date" name="purchasedate" required><br><br>
        
        <label>purchase time:</label>
        <input type="time" name="purchasetime" required><br><br>
        
        <div id="items">
            <div class="item">
                <label>short description:</label>
                <input type="text" name="shortdescription[]" required>
                
                <label>price:</label>
                <input type="number" name="price[]" step="0.01" min="0" required>
            </div>
        </div>
        <button type="button" id="add-item-btn">add item</button><br><br>
        
        <label>total:</label>
        <input type="number" name="total" step="0.01" min="0" required><br><br>
        
        <button type="submit">submit</button>
    </form>

    <script>
        $(document).ready(function() {
            var itemcount = 1;
            $('#add-item-btn').click(function() {
                itemcount++;
                var newitem = '<div class="item"><label>short description:</label>' +
                    '<input type="text" name="shortdescription[]" required>' +
                    '<label>price:</label>' +
                    '<input type="number" name="price[]" step="0.01" min="0" required>' +
                    '<button type="button" class="remove-item-btn">remove item</button>' +
                    '</div>';
                $('#items').append(newitem);
            });
            
            $(document).on('click', '.remove-item-btn', function() {
                $(this).parent().remove();
                itemcount--;
            });
            
            $('#receipt-form').submit(function(event) {
                event.preventdefault();
                var form = $(this).serializearray();
                var items = [];
                $('.item').each(function() {
                    var item = {};
                    item.shortdescription = $(this).find('input[name="shortdescription[]"]').val();
                    item.price = $(this).find('input[name="price[]"]').val();
                    items.push(item);
                });
                form.push({ name: "items", value: json.stringify(items) });
                $.ajax({
                    type: "post",
                    url: "/submit",
                    data: form,
                    success: function(response) {
                        window.location.href = "/receipt?id=" + response.receiptid;
                    },
                    error: function(xhr, status, error) {
                        console.log(xhr.responsetext);
                    }
                });
            });
        });
    </script>
</body>
</html>

這是我的receipt.html,這是提交收據後的收據頁面的html。

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Receipt Details</title>
</head>
<body>
    <h1>Receipt Details</h1>
    <ul>
        <li>Retailer: {{.Retailer}}</li>
        <li>Purchase Date: {{.PurchaseDate}}</li>
        <li>Purchase Time: {{.PurchaseTime}}</li>
        <li>Items:</li>
        <ul>
            {{range .Items}}
            <li>{{.ShortDescription}} - {{.Price}}</li>
            {{end}}
        </ul>
        <li>Total: {{.Total}}</li>
    </ul>
</body>
</html>

我嘗試了不同的序列化方法,但沒有任何效果。當我填寫收據表格然後點擊提交時,我希望我會進入收據頁面,顯示該收據的獨特詳細資訊。但是我剛剛收到一個錯誤,我最近的一個錯誤是這樣的: in無效字元「r」尋找值的開頭

解決方法

請如下更新您的 home.html。我將提交請求內容類型更改為 application/json 因為伺服器中的 submithandler 正在尋找 json

$('#receipt-form').submit(function(event) {
    event.preventDefault();
    
    var form = $(this).serializeArray();

    var formObject = {};
    $.each(form,
        function(i, v) {
            if (v.name != "price[]" && v.name != "shortDescription[]") {
                formObject[v.name] = v.value;
            }
        });

    var items = [];
    $('.item').each(function() {
        var item = {};
        item.shortDescription = $(this).find('input[name="shortDescription[]"]').val();
        item.price = $(this).find('input[name="price[]"]').val();
        items.push(item);
    });

    formObject["items"] = items;

    $.ajax({
        type: "POST",
        url: "/submit",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        data: JSON.stringify(formObject),
        success: function(response) {
            window.location.href = "/receipt?id=" + response.receiptID;
        },
        error: function(xhr, status, error) {
            console.log(xhr.responseText);
        }
    });
});

以上是無法正確地將表單序列化為 json的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除