ajax - Golang、Ajax - 如何在成功函数中返回 slice 或结构?

标签 ajax go beego

我的问题与this link.中的问题类似我需要将多个 slice 或一个结构从 golang 返回到 ajax 成功 block 。我试图将我的 slice 编码为 JSON,但它在 ajax 中作为字符串接收。我需要将它作为数组接收。是否可以像这样发送多个数组或结构?

我的代码:

b, _ := json.Marshal(aSlice)      // json Marshal
c, _ := json.Marshal(bSlice)
this.Ctx.ResponseWriter.Write(b) // Beego responsewriter
this.Ctx.ResponseWriter.Write(c)

我的 Ajax :

$.ajax({
        url: '/delete_process',
        type: 'post',
        dataType: 'html',
        data : "&processName=" + processName,
        success : function(data) {
            alert(data);
            alert(data.length)
        }
});

提前致谢。

最佳答案

ajax 请求的dataType 参数应该是json,因为您期望来自服务器的JSON 数据。但是,如果您的服务器未使用有效的 JSON 进行响应,则 ajax 请求将导致错误。检查浏览器的 javascript 控制台是否有错误。

从您当前在 Controller 中所做的事情来看,它肯定会导致无效的 JSON 响应。见下文。

aSlice := []string{"foo", "bar"}
bSlice := []string{"baz", "qux"}

b, _ := json.Marshal(aSlice) // json Marshal
c, _ := json.Marshal(bSlice)

this.Ctx.ResponseWriter.Write(b) // Writes `["foo","bar"]`
this.Ctx.ResponseWriter.Write(c) // Appends `["baz","qux"]`

这导致发送 ["foo","bar"]["baz","qux"] 这只是两个附加在一起的 JSON 数组字符串。它无效。

您可能想发送给浏览器的是:[["foo","bar"],["baz","qux"]]

那是两个数组的数组。您可以执行此操作以从服务器发送它。

aSlice := []string{"foo", "bar"}
bSlice := []string{"baz", "qux"}

slice := []interface{}{aSlice, bSlice}

s, _ := json.Marshal(slice) 
this.Ctx.ResponseWriter.Write(s) 

在 javascript 方面,

$.ajax({
        url: '/delete_process',
        type: 'post',
        dataType: 'json',
        data : "&processName=" + processName,
        success : function(data) {
            alert(data);
            alert(data[0]);    // ["foo","bar"]
            alert(data[1]);    // ["baz","qux"]
            alert(data.length) // 2
        }
});

关于ajax - Golang、Ajax - 如何在成功函数中返回 slice 或结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37412187/

相关文章:

jquery - 415 在 ajax 调用 Spring mvc 中发送 json 对象时不支持的媒体类型

javascript - 使用 ajax 进行黑客攻击 html 编码

http - 如何检查错误是否是Go中的tls握手超时

json - 在 golang 中存储和检索接口(interface)

go - ImageMagick Go API HTTP 在 ReadImageBlob 上挂起

Jquery Ajax CORS + HttpOnly Cookie

javascript - 无法发送 CORS 查询 : responds with "No ' Access-Control-Allow-Origin' header"

go - Beego orm - 关系不起作用

Golang 中的函数声明

url - Go或Beego是否支持像id=这样的动态url路由?