douren5898 2018-05-04 05:31 采纳率: 100%
浏览 53

如何使用ajax从go api检索数据?

I'm retrieving the data using ajax from golang api but in ajax success function the response is not returning the user data while golang will returning it. Below is the ajax I'm using:

$(document).ready(function(){
    $.ajax({
        url:"/api/v1/customer/:id",
        type: "GET",
        success: function(results){
            console.log(results) //it will not retrieving the data
        }
    });
});

Output of ajax

//nothing

here is the golang router:

Route{"GetFullCustomer", "GET", "/customer/:id", controller.GetCustomer}
// when I will hit this url then the function GetCustomer will run.
v1 := router.Group("/api/v1") // there is also grouping

Here is the function which is retrieving the user:

func GetCustomer(c *gin.Context) {
  t, _ := template.ParseFiles("index.html")
  t.Execute(c.Writer, nil)
  customerIdString := c.Param("id")  //taking the id from url
  customerId, err := strconv.Atoi(customerIdString)
  mongoSession := config.ConnectDb()
  collection := mongoSession.DB("customer").C("customercollection")
  pipeline := []bson.M{
    bson.M{"$match": bson.M{"_id": customerId}},
    bson.M{"$lookup": bson.M{"from" : "address", "localField" : "_id", "foreignField": "user_id","as": "address" }},
    // bson.M{"$project":bson.M{"_id":0}}
  }
  pipe := collection.Pipe(pipeline)
  resp := []bson.M{}
  err = pipe.All(&resp)
  if err != nil {
     fmt.Println("Errored: %#v 
", err)
  }
 c.JSON(200, gin.H{"data": resp})
}

by hitting the url of localhost http://localhost:8080/api/v1/customer/1 Output of terminal is:

[GIN] 2018/05/04 - 12:40:11 | 200 |   11.200709ms |             ::1 | GET      /api/v1/customer/1
[map[$match:map[_id:0]] map[$lookup:map[from:address localField:_id foreignField:user_id as:address]]]
[]
[GIN] 2018/05/04 - 12:40:11 | 200 |    6.986699ms |             ::1 | GET      /api/v1/customer/Person.png
[map[$match:map[_id:0]] map[$lookup:map[foreignField:user_id as:address from:address localField:_id]]]
[]
[GIN] 2018/05/04 - 12:40:12 | 200 |    1.619845ms |             ::1 | GET      /api/v1/customer/:id

Issue is that while golang url hit show above the golang will take the /:id dynamically and matches the data but the ajax don't take this id dynamically. So how I will resolve my problem.

  • 写回答

1条回答 默认 最新

  • dounieqi6959 2018-05-04 05:49
    关注

    It may be silently failing. You need to check the Developer Tools in your browser. In Chrome there is a Network tab which shows info about each AJAX request. It is likely that the AJAX call is failing for some reason and you need to get find out what the error is. You'll probably see it in the Console tab as well.

    Also, just noticed that dataType is set to "html", which seems incorrect based on the output format you described. It should probably be "json".

    You should handle failures in your AJAX requests so that the user knows there is a problem. Here is some code to get you started:

    $(document).ready(function(){
        var promise = $.ajax({
            url:"/api/v1/customer/:id",
            type: "GET",
            dataType: 'json'
        });
    
        promise.done(function(data) {
            console.log(data);
        });
    
        promise.fail(function(jqXHR, textStatus, errorThrown) {
            console.log("Request failed. jqXHR.status=" + jqXHR.status + ", textStatus=" + textStatus + ", errorThrown=" + errorThrown);
        });
    });
    
    评论

报告相同问题?

悬赏问题

  • ¥20 数学建模,尽量用matlab回答,论文格式
  • ¥15 昨天挂载了一下u盘,然后拔了
  • ¥30 win from 窗口最大最小化,控件放大缩小,闪烁问题
  • ¥20 易康econgnition精度验证
  • ¥15 msix packaging tool打包问题
  • ¥28 微信小程序开发页面布局没问题,真机调试的时候页面布局就乱了
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能