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条)

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度