1

相当多的链接,但我无法将所有信息拼凑在一起。

我假设涉及一个控制器、一个视图和路由。

关于 url 和路由,我有通用文件夹结构,app/views/pages/home 和 app/controllers/pages_controller.rb。如果我正确地执行路由和 url,你能指导我吗?

路线.rb

get pages/get_aj //Don't know if this is what you put

jQuery

$.ajax({ 
type: 'get'
url: '/pages/get_aj' //can someone confirm this is how you do it? 
dataType: "JSON" //I need to pass back values from the controller to JS. Do I use JSON?
}).success(function(data){
      alert("returned " + data);
});

//some other jQuery code that will depend on the data returned.

pages_controller.rb

def get_aj
   respond_to do |format|
      format.json{render :json => "we got here" } //Do I return .js?
   end
end

耙路线

   pages_home GET /pages/home(.:format)    pages#home
pages_contact GET /pages/contact(.:format) pages#contact
 pages_get_aj GET /pages/get_aj(.:format)  pages#get_aj
4

1 回答 1

6

您的代码应该实际工作。你最大的误解是 JS alert 的作用。它警告字符串,并且data是一个对象。看到这个 JS 小提琴:http: //jsfiddle.net/YNeA3/

要从 JS 检查对象,请使用console.log()而不是警报。这些将显示在您的浏览器控制台中。这是基本的 JS 调试工具。

我不确定您发送的 JSON 对象是什么样的,因为您应该渲染一个哈希,而不是一个字符串。我认为这是您的代码唯一真正的问题。

另外,建议:如果此控制器操作仅用于 ajax,则您不必打扰 respond_to 块。我会指定状态。

def get_aj
  data = {:message => "Alert this!"}
  render :json => data, :status => :ok
end

现在在你的 JS 中:

$.ajax({ 
  type: 'GET',
  url: '/pages/get_aj',
  success: function(data,status,xhr){
    console.log(data);
    alert(data.message);
  },
  error: function(xhr,status,error){
    console.log(xhr);
    alert(error);
  }
});

数据将是一个 JS 对象,看起来就像您发送的哈希一样。

于 2013-06-19T16:27:07.380 回答