我有js文件:
$('#some_btn').click(function() {
var valuesToSubmit = $('#some_form').serialize();
var url = $('#some_form').attr('action');
console.log("VALUE: " + valuesToSubmit);
console.log("URL: " + search_url);
$.ajax({
type: 'POST',
url: url, //sumbits it to the given url of the form
data: valuesToSubmit,
dataType: "JSON",
success: function(data) {
console.log("saved");
console.log(data);
}
});
return false;
});
响应的控制器操作:
def some_action()
...
@response = {resp: "ack"}
respond_with @response do |format|
format.json { render :layout => false, :text => @response }
end
end
路线:
post '/abc/some_action', to: 'abc#some_action'
但执行后我收到:
ArgumentError
Nil location provided. Can't build URI.
@response = {resp: "ack"}
respond_with @response do |format| # <--- Error here
format.json { render :layout => false, :text => @response }
end
答案 0 :(得分:2)
respond_with
需要一个可以推导出路线的AR对象。
更改为:
@response = {resp: "ack"}
respond_to do |format|
format.json { render json: @response }
format.js { render json: @response }
end
另一种方法是强制控制器仅为特定动作渲染json。很奇怪,因为这意味着你无法发送正确的请求。
但在这种情况下:
respond_to :json, :only => :some_action
在你的行动中:
render json: @response
答案 1 :(得分:0)
在您的控制器中添加此行
class YourController < ...
respond_to :json
然后
@response = {resp: "ack"}
respond_with(@response)