首页 > 解决方案 > 如何使用 ajax 从 go api 检索数据?

问题描述

我正在使用来自 golang api 的 ajax 检索数据,但是在 ajax 成功函数中,响应没有返回用户数据,而 golang 将返回它。下面是我正在使用的ajax:

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

ajax的输出

//nothing

这是golang路由器:

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

这是检索用户的函数:

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 \n", err)
  }
 c.JSON(200, gin.H{"data": resp})
}

通过点击 localhost 的 urlhttp://localhost:8080/api/v1/customer/1终端的输出是:

[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

问题是,虽然 golang url hit show 上面的 golang 将/:id动态获取并匹配数据,但 ajax 不会动态获取此 id。那么我将如何解决我的问题。

标签: ajaxgo

解决方案


它可能会默默地失败。您需要在浏览器中检查开发人员工具。在 Chrome 中,有一个 Network 选项卡,其中显示有关每个 AJAX 请求的信息。AJAX 调用很可能由于某种原因而失败,您需要找出错误所在。您可能还会在“控制台”选项卡中看到它。

另外,刚刚注意到 dataType 设置为“html”,根据您描述的输出格式,这似乎不正确。它可能应该是“json”。

您应该处理 AJAX 请求中的失败,以便用户知道存在问题。以下是一些帮助您入门的代码:

$(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);
    });
});

推荐阅读