搜索
首页后端开发Golang无法正确地将表单序列化为 json

无法正确地将表单序列化为 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 id="receipt-input-form">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 id="Receipt-Details">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”寻找值的开头in无效字符“r”寻找值的开头

解决方法

请按如下方式更新您的 home.html。我将提交请求内容类型更改为 application/json 因为服务器中的 submithandler 正在寻找 json

解决方法🎜🎜请按如下方式更新您的 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。如有侵权,请联系admin@php.cn删除
Golang和Python:了解差异Golang和Python:了解差异Apr 18, 2025 am 12:21 AM

Golang和Python的主要区别在于并发模型、类型系统、性能和执行速度。1.Golang使用CSP模型,适用于高并发任务;Python依赖多线程和GIL,适合I/O密集型任务。2.Golang是静态类型,Python是动态类型。3.Golang编译型语言执行速度快,Python解释型语言开发速度快。

Golang vs.C:评估速度差Golang vs.C:评估速度差Apr 18, 2025 am 12:20 AM

Golang通常比C 慢,但Golang在并发编程和开发效率上更具优势:1)Golang的垃圾回收和并发模型使其在高并发场景下表现出色;2)C 通过手动内存管理和硬件优化获得更高性能,但开发复杂度较高。

Golang:云计算和DevOps的关键语言Golang:云计算和DevOps的关键语言Apr 18, 2025 am 12:18 AM

Golang在云计算和DevOps中的应用广泛,其优势在于简单性、高效性和并发编程能力。1)在云计算中,Golang通过goroutine和channel机制高效处理并发请求。2)在DevOps中,Golang的快速编译和跨平台特性使其成为自动化工具的首选。

Golang和C:了解执行效率Golang和C:了解执行效率Apr 18, 2025 am 12:16 AM

Golang和C 在执行效率上的表现各有优势。1)Golang通过goroutine和垃圾回收提高效率,但可能引入暂停时间。2)C 通过手动内存管理和优化实现高性能,但开发者需处理内存泄漏等问题。选择时需考虑项目需求和团队技术栈。

Golang vs. Python:并发和多线程Golang vs. Python:并发和多线程Apr 17, 2025 am 12:20 AM

Golang更适合高并发任务,而Python在灵活性上更有优势。1.Golang通过goroutine和channel高效处理并发。2.Python依赖threading和asyncio,受GIL影响,但提供多种并发方式。选择应基于具体需求。

Golang和C:性能的权衡Golang和C:性能的权衡Apr 17, 2025 am 12:18 AM

Golang和C 在性能上的差异主要体现在内存管理、编译优化和运行时效率等方面。1)Golang的垃圾回收机制方便但可能影响性能,2)C 的手动内存管理和编译器优化在递归计算中表现更为高效。

Golang vs. Python:申请和用例Golang vs. Python:申请和用例Apr 17, 2025 am 12:17 AM

selectgolangforhighpperformanceandcorrency,ifealforBackendServicesSandNetwork程序; selectpypypythonforrapiddevelopment,dataScience和machinelearningDuetoitsverserverserverserversator versator anderticality andextility andextentensivelibraries。

Golang vs. Python:主要差异和相似之处Golang vs. Python:主要差异和相似之处Apr 17, 2025 am 12:15 AM

Golang和Python各有优势:Golang适合高性能和并发编程,Python适用于数据科学和Web开发。 Golang以其并发模型和高效性能着称,Python则以简洁语法和丰富库生态系统着称。

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
1 个月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
1 个月前By尊渡假赌尊渡假赌尊渡假赌
威尔R.E.P.O.有交叉游戏吗?
1 个月前By尊渡假赌尊渡假赌尊渡假赌

热工具

MinGW - 适用于 Windows 的极简 GNU

MinGW - 适用于 Windows 的极简 GNU

这个项目正在迁移到osdn.net/projects/mingw的过程中,你可以继续在那里关注我们。MinGW:GNU编译器集合(GCC)的本地Windows移植版本,可自由分发的导入库和用于构建本地Windows应用程序的头文件;包括对MSVC运行时的扩展,以支持C99功能。MinGW的所有软件都可以在64位Windows平台上运行。

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript开发工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

功能强大的PHP集成开发环境

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器