Search code examples
ajaxgobeego

Golang, Ajax - How to return slices or struct in a success function?


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.


Solution

  • 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
            }
    });