Ajax 成功处理程序 - 数据未定义

Ajax success handler - data is undefined

本文关键字:数据 未定义 程序 成功 处理 Ajax      更新时间:2023-09-26

这是我发出ajax请求的方式

  #action
  def get_item
    if request.get?
      binding.pry  #it always stop here, so it's working
      item = Item.where(...)
      unless item
        item = Item.new
        # .....
      end
      respond_to do |format| 
        format.json { render(json: item) } 
      end
    elsif request.post?
       # ......
    end
  end
  #view
     $.ajax({
          type: "GET",
          url: "/contr/get_item",
                data: {key1: "value1"},
                //datatype: "json",
                success: function(data){
                  console.log("ajax success, data -> " + data[0]);
                    }
             });

尽管执行了get_item中的代码,但页面上的data值始终undefined

我错过了什么?

p.s. 请注意,请求是从 json 中的服务器发回的。我可以通过单击F12并转到"网络"选项卡的"调试工具"在Chrome中看到它。

试试这个:

 def get_item
   if request.get?
     item = Item.where(...)
     unless item
       item = Item.new
       # .....
     end
     render :json => item.to_json
   elsif request.post?
    #...
   end
 end

视图

   $.ajax({
      type: "GET",
      url: "/contr/get_item",
            data: {key1: "value1"},
            //datatype: "json",
            success: function(data){
              console.log("ajax success, data -> " + data[0]);
                }
         });

您的 URL 需要说明您要使用的格式。在您的情况下,它应该以 .json 结尾,以便在 json 中做出响应。

#view
   $.ajax({
        type: "GET",
        url: "/contr/get_item.json",