ajax在rails中调用数据库

时间:2016-01-12 09:31:39

标签: ruby-on-rails ajax

我正在尝试获取与var匹配的行,在我的情况下是一个url。在数据库中并以json格式返回整行。

基本上,如果table1中的url匹配table2中eventurl下的url。然后整行作为jsonformat传递给ajax请求。

到目前为止我所拥有的。

的routes.rb

resources :gig do
    scope constraints: { format: "json" } do
      get :gigdata, on: :member
    end
  end

在我的ajax电话中,我有这个

url: 'gigdata/' + gigurlofevent , (no need to include the whole url ajax file here as its working elsewhere)

在我的控制器中我有这个

  respond_to :json, only: :gigdata
   def gigdata
    gig = Gigstable.where(eventurl: (params[:gigurlofevent]))
    render json: gig
   end

现在,我不能用一个byebug进入gigdata。

我想知道我需要做什么/我错过了什么

由于 萨姆

修改

继续ajax调用成功函数的开始

$.ajax({
        beforeSend: function(xhr) {
            xhr.setRequestHeader("Content-Type", "application/json");
        },
        type: 'GET',
        crossDomain: true,
        dataType: 'json',
        url: 'gigdata/' + gigurlofevent ,
        success: function(json) {
            debugger;

1 个答案:

答案 0 :(得分:0)

常见问题:

您写道:

  

(不需要在此处包含整个url ajax文件作为其工作   别处)

实际上,您需要包含完整的代码,因为常见问题存在于Content-Type字段中。您需要在标题中指定请求的内容类型,例如' application / json'。

我正在使用curl测试我的后端api 例如:

curl http://localhost/api/v1/some_action -H 'Content-Type: application/json' -vvv

最后一个参数-vvv对于调试请求非常有用,因为它使curl在控制台中输出带有标题的请求和响应。


调试ajax的另一种方法

打开开发人员工具(对于Chrome它来说: F12 ctrl + shift + i ),单击网络选项卡,然后单击XHR过滤器按钮。使用ctrl+r重新加载页面并再次执行您的ajax请求。有关您的ajax请求的信息将显示在过滤器下方的窗口中。现在您可以查看来自服务器的数据类型以及哪些是错误的。


黄金法则

Rails服务器在控制台中输出所有请求。当某些东西不像你期望的那样,不要害羞地阅读输出。