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

报告相同问题?