使用Golang结合AJAX实现字符串处理的实践方法

使用Golang结合AJAX实现字符串处理的实践方法 在使用我的输入ID变量并通过Ajax将其传递给JavaScript页面时,被调用函数中的值为:[[object HTMLInputElement]]。我无法获取其真实值,即使使用点值(.value)也不行,descID是变量。

stringforhtmldiv = "<center><button id = \"\" onclick = \"SaveProductItems(" + descID + ")\"</button></center>"

我也尝试过在剩余的引号上使用反斜杠,并使用了模板。

8 回复

好的

更多关于使用Golang结合AJAX实现字符串处理的实践方法的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


哦,天哪,整个事情,好吧,给我一点时间……

很抱歉带来了麻烦,我已经学会了更好的求助方法。

你好,Joshua,我不太明白你的意思。你能提供一个我们可以运行、测试和排查问题的例子吗?

嗯,你的代码存在一些错误和一些不良实践。其中之一是在HTTP处理程序中创建数据库连接。此外,尝试使用模板而不是拼接字符串来生成HTML输出。

我想你可能也需要数据库……(如果我可以提供的话)

好的,针对这个问题,将 index 函数修改为这样:

func index(w http.ResponseWriter, r *http.Request) {

	db := dbConn()
	receiveAjax(w, r)
	
}
func receiveAjax(w http.ResponseWriter, r *http.Request) {

	
	const string = "<center><button id = \"\" onclick = \"SaveProductItems(" + descID + ")\"></button>"
	
	// Prepare some data to insert into the template.
	type Test1 struct {
		Desc string
	}

	rec1 := Test1{"desc2"}

	t := template.Must(template.New("letter").Parse(letter))
	//var Buf bytes.Buffer("a")

	var tpl bytes.Buffer

	if err := t.Execute(&tpl, rec1); err != nil {
		//Handle error
	}

	if r.Method == "POST" {
		data := r.FormValue("post_data")
		fmt.Println("Receive ajax post data string ", data)
		w.Header().Add("Content-Type", "application/html")
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
		w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
		w.Write([]byte(tpl.String()))

	}
}

func main() {
	mux := http.NewServeMux()
	//mux.HandleFunc("/receive", receiveAjax)

	mux.HandleFunc("/receive", index)

	http.ListenAndServe(":8080", mux)
}
<head>

    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
  <!DOCTYPE html>
</head>  


<div class="jumbotron text-center">
    <h1>Online Store</h1>
    <p>Resize this responsive page to see the effect!</p>
    <p>https://www.w3schools.com/bootstrap4/tryit.asp?filename=trybs_default&stacked=h</p>
  </div>


<script>
function SaveProductItems(a)
{
  /////////////////////////////////////////////////////
  /////////////////////////////////////////////////////
  ////document.getElementById(a).value: DOESNT WORK?!?!;  Cant get the real value
  /////////////////////////////////////////////////////
  /////////////////////////////////////////////////////
    alert (a);
}
</script>     


        <div id='div1'></div>      
        </div></div></div>
        <script>
            $(document).ready(function () {
                $('#button1').click(function () {
                    $.ajax({
                        url: 'http://127.0.0.1:8080/receive',
                        type: 'post',
                        dataType: 'html',
                        contentType: 'application/x-www-form-urlencoded',
                        crossDomain: true,
                        data: {post_data: 'hello world'},
                        success: function (data) {
                            const jsonBytesToString = String.fromCharCode(data);

// 1
                          console.log("Bytes as a string: ", jsonBytesToString);

                            console.log(data);
                            $('#div1').html(data);
                        }
                    });
                });
            });
        </script>
</head>
<body>

在Go中生成JavaScript代码时,需要特别注意HTML属性和JavaScript字符串的转义。您遇到的问题是descID变量在JavaScript中被直接输出为对象,而不是其值。以下是正确的实现方法:

方法1:使用html/template包(推荐)

package main

import (
    "html/template"
    "os"
)

func main() {
    // 定义模板
    const buttonTemplate = `<center>
        <button onclick="SaveProductItems({{.DescID}})">保存</button>
    </center>`
    
    // 创建模板
    tmpl, err := template.New("button").Parse(buttonTemplate)
    if err != nil {
        panic(err)
    }
    
    // 数据
    data := struct {
        DescID string
    }{
        DescID: "product123", // 您的descID值
    }
    
    // 执行模板
    err = tmpl.Execute(os.Stdout, data)
    if err != nil {
        panic(err)
    }
}

方法2:手动转义(不推荐,仅用于演示)

package main

import (
    "fmt"
    "html"
)

func generateButton(descID string) string {
    // 对descID进行HTML转义
    escapedDescID := html.EscapeString(descID)
    
    // 生成HTML
    return fmt.Sprintf(
        `<center><button onclick="SaveProductItems('%s')">保存</button></center>`,
        escapedDescID,
    )
}

func main() {
    descID := "product123"
    htmlOutput := generateButton(descID)
    fmt.Println(htmlOutput)
}

方法3:使用JavaScript模板字面量(如果descID是字符串)

package main

import (
    "fmt"
    "html"
)

func generateButtonWithJS(descID string) string {
    // 对descID进行HTML转义
    escapedDescID := html.EscapeString(descID)
    
    // 使用JSON编码确保正确的JavaScript字符串
    return fmt.Sprintf(
        `<center>
            <button onclick="SaveProductItems(%s)">保存</button>
        </center>`,
        fmt.Sprintf(`"%s"`, escapedDescID),
    )
}

func main() {
    descID := "product123"
    htmlOutput := generateButtonWithJS(descID)
    fmt.Println(htmlOutput)
}

完整的AJAX示例

Go后端处理:

package main

import (
    "encoding/json"
    "html/template"
    "net/http"
)

type Product struct {
    ID   string `json:"id"`
    Name string `json:"name"`
}

func main() {
    // 静态文件服务
    fs := http.FileServer(http.Dir("./static"))
    http.Handle("/static/", http.StripPrefix("/static/", fs))
    
    // 主页
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        tmpl := template.Must(template.ParseFiles("index.html"))
        products := []Product{
            {ID: "prod1", Name: "产品1"},
            {ID: "prod2", Name: "产品2"},
        }
        tmpl.Execute(w, products)
    })
    
    // AJAX端点
    http.HandleFunc("/save", func(w http.ResponseWriter, r *http.Request) {
        productID := r.URL.Query().Get("id")
        // 处理保存逻辑
        response := map[string]string{
            "status":  "success",
            "message": "产品 " + productID + " 已保存",
        }
        
        w.Header().Set("Content-Type", "application/json")
        json.NewEncoder(w).Encode(response)
    })
    
    http.ListenAndServe(":8080", nil)
}

HTML模板(index.html):

<!DOCTYPE html>
<html>
<head>
    <title>产品管理</title>
</head>
<body>
    <h1>产品列表</h1>
    {{range .}}
    <div class="product-item">
        <span>{{.Name}}</span>
        <button onclick="saveProduct('{{.ID}}')">保存</button>
    </div>
    {{end}}
    
    <script>
    function saveProduct(productId) {
        // 使用AJAX发送请求
        fetch('/save?id=' + encodeURIComponent(productId))
            .then(response => response.json())
            .then(data => {
                alert(data.message);
            })
            .catch(error => {
                console.error('错误:', error);
            });
    }
    
    // 或者如果需要在其他地方调用
    function SaveProductItems(descID) {
        console.log('产品ID:', descID);
        // 这里可以调用saveProduct函数
        saveProduct(descID);
    }
    </script>
</body>
</html>

关键点:

  1. 使用html/template包自动处理HTML转义
  2. 在JavaScript中确保字符串被正确引用
  3. 避免在Go中拼接HTML字符串,使用模板引擎
  4. 在AJAX调用中正确编码URL参数
回到顶部