[英]Passing values between jQuery and Controller Rails
链接很多,但是我无法将所有信息拼凑在一起。
我假设涉及到控制器,视图和路由。
关于url和路由,我有通用的文件夹结构app / views / pages / home和app / controllers / pages_controller.rb。 如果我正确地进行路由和URL,也可以引导我吗?
routes.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
您的代码应实际工作。 您最容易误解的是JS Alert的功能。 它警告字符串,并且data
是一个对象。 看到这个JS小提琴: http : //jsfiddle.net/YNeA3/
要从JS检查对象,请使用console.log()
而不是alert。 这些将显示在您的浏览器控制台中。 这是用于JS的基本的黄油调试工具。
我不确定您要发送的JSON对象是什么样的,因为您应该呈现一个哈希,而不是字符串。 我认为这是您的代码唯一真正的问题。
另外,还有一个建议:如果此控制器操作仅用于ajax,则无需理会response_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对象,看起来像您发送的哈希。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.