我正在尝试使用 jquery 向我的 Rails 发出 POST 请求。
我对 ajax 调用的值(value)观
$('input[type=submit]').unbind().bind('click', function() {
// extract category id from hidden field
var category = $("#category_id").val();
var category_id = category.split("=>").pop(-1);
category_id = category_id.replace("}","");
// extract question id from hidden field
var question = $("#question_id").val();
var question_id = question.split("=>").pop(-1);
question_id = question_id.replace("}","");
// init new array to pass choices
var checked = [];
$("input:checked").each(function() {
var whole_id = $(this).attr("id");
var id = whole_id.split("_").pop(-1);
checked.push(id);
});
var answers = JSON.stringify(checked);
console.log(checked);
retrieve(answers,category_id,question_id);
});
ajax调用
function retrieve(answers,category,question) {
$.ajax({
cache: false,
type: "POST",
url: "/categories/" + category + "/questions/" + question + "/retrieve",
data: answers,
success: function(data) {
},
error: function(xhr) {
alert("The error code is: " + xhr.statusText);
}
});
};
路由
resources :categories do
get '/random_question', action: 'random_question', controller: 'categories', as: 'random_question'
resources :questions do
post '/retrieve', to: 'questions#retrieve'
resources :choices, only: [:index]
end
end
Controller
def retrieve
@category = Category.find_by(params[:category_id])
respond_to do |format|
format.html { redirect_to category_questions_url, notice: 'success' }
format.json {
render json: {
message: "success"
}
}
end
end
我收到 404 错误(未找到),网址如下
http://localhost:3000/categories/%222%22/questions 404 (Not Found)
这是错误的。
也在 Chrome 开发工具的网络选项卡中我得到了这个
ActiveRecord::RecordNotFound in QuestionsController#index
Couldn't find Category with 'id'="2"
最佳答案
刚刚注意到您发送的category_id 和question_id 作为字符串,而不是数字。而不是棘手的黑客:
// extract category id from hidden field
var category = $("#category_id").val();
var category_id = parseInt(category);
// extract question id from hidden field
var question = $("#question_id").val();
var question_id = parseInt(question);
而且它应该是金色的。在控制台中尝试了您的方法,但它仍然返回一个字符串,这就是您的问题
关于javascript - Ajax url 参数未正确附加 - Rails 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32566445/