使用Ajax请求Rails控制器数据 [英] Use Ajax to request for rails controller data

查看:70
本文介绍了使用Ajax请求Rails控制器数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有人可以帮助我解决这个问题,并提供可能的解释.我有一个名为get_songs的rails控制器,它将从当前登录的用户获取歌曲的哈希值.也就是说,每当单击特定按钮时,我都希望从get_songs控制器获取数据,并将其放在javascript变量中.以下是我到目前为止的内容.

I was hoping someone could help me out on this one, and a possible explanation. I have a rails controller called get_songs that will get a hash of songs from the currently logged in user. That said, whenever a particular button is clicked I want to get the data from the get_songs controller at put it in javascript variable. The following is what I have so far.

playlist.js.erb

   function get_songs() {
 var mysongs;
 $.ajax({
    type : 'GET',
    url : "getSongs",
    dataType : 'json',
    success : function(response) {
    }
  });
}

我的控制人

class StaticPagesController < ApplicationController


  respond_to :js, :json, :html

 def get_songs()
      if user_signed_in?
            session[:user_id] = current_user.id
            present_user = User.find(session[:user_id])
            present_user = present_user.playlist.keys
        @songs = present_user
    respond_to do |format|
  format.json  { render :json => @songs}

    end
    end

我的路线:

  match '/getSongs', to: 'static_pages#get_songs', via: 'get'

推荐答案

如果一切正常,您可以这样做:

If everything was working you would do:

success : function(response) {
  mysongs = response;
}

成功函数上的'response'参数是您从控制器发送的ajax调用的结果; @songs json.

The 'response' parameter on the success function is the result of the ajax call you are sending from your controller; the @songs json.

一种简单的调试javascript的方法(检查ajax请求后响应"的值是什么)是右键单击浏览器,然后单击检查",然后转到源"选项卡,查找您的javascript文件,然后单击要添加调试点的行(在本例中为"mysongs = response"的行,然后刷新页面.它应在该点停止运行并显示"response"的值'.

A simple way to debug your javascript (to check what is the value of your 'response' after the ajax request) is to right-click on your browser and click on 'inspect', then go to the 'Sources' tab, look for your javascript file and click the line where you want to add the debug point (in this case the line with 'mysongs = response', then refresh the page. It should stop running at that point and show the value of 'response'.

这篇关于使用Ajax请求Rails控制器数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆