doutan8775 2016-05-24 11:25
浏览 75
已采纳

Golang,Ajax-如何在成功函数中返回切片或结构?

My problem is similar to that of the question in this link. I need to return multiple slices or a struct from golang to the ajax success block. I tried to marshal my slice into JSON but it is received in ajax as a string. I need to receive it as an array. Is it possible to send multiple arrays or a struct like this?

My code:

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

My ajax:

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

Thanks in advance.

  • 写回答

2条回答 默认 最新

  • drlndkhib08556095 2016-05-24 13:04
    关注

    The dataType parameter of your ajax request should be json as you are expecting JSON data from the server. But if you server does not respond with valid JSON the ajax request is going to result in an error. Check your browser's javascript console for errors.

    From what you are currently doing in the controller, its definitely going to result in invalid JSON response. See following.

    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"]`
    

    This results in sending ["foo","bar"]["baz","qux"] Thats just two JSON array strings appended together. Its not valid.

    What you probably want to send to browser is this: [["foo","bar"],["baz","qux"]].

    That is an array of two arrays. You can do this to send it from the server.

    aSlice := []string{"foo", "bar"}
    bSlice := []string{"baz", "qux"}
    
    slice := []interface{}{aSlice, bSlice}
    
    s, _ := json.Marshal(slice) 
    this.Ctx.ResponseWriter.Write(s) 
    

    And in the javascript side,

    $.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
            }
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?