我正在尝试通过 Rails 中的 AJAX 提交表单,但我不太确定这里出了什么问题。我使用“remote: true”让一切正常工作,但我想更好地了解 AJAX 如何与 jQuery 配合使用。这是我的 JavaScript 代码:
$(document).ready(function(){
$("#new_user_friendship").on("submit", function(event){
event.preventDefault();
var friendId = $("#user_friendship_friend_id").val();
var _this = $(this);
$.ajax({
url: "/user_friendships",
data: _this.serialize(),
method: "POST",
dataType: "json",
success: function(data){
console.log(data);
friendButton.hide();
$(".friend-request-form").html("<p>Friend request sent</p>");
}
});
});
});
我怀疑包含 url 的这一行 url: "/user_friendships/new?friend_id="+friendId
是我的错误的罪魁祸首。我写这个是因为隐藏字段被作为一个人的 friend ID 传递,但它会抛出“404 错误”,我也尝试过 url: "/user_friendships"
它不会返回任何错误,但它也没有像我预期的那样正确执行 Javascript。
这是 AJAX 请求发送到的相应 form_for:
<div class="friend-request-form">
<%= form_for current_user.user_friendships.build(friend_id: @user), id: "new_user_friendship", method: :post do |f| %>
<%= f.hidden_field :friend_id, value: @user.id %>
<%= submit_tag "Send friend request", class: "button radius tiny", id: "friend-request-button" %>
<% end %>
</div>
此表单的作用是使用隐藏字段向另一个用户发送好友请求。
在我的 user_friendships_controller.rb 中,我有以下代码:
def create
if params[:user_friendship] && params[:user_friendship].has_key?(:friend_id)
@friend = User.find(params[:user_friendship][:friend_id])
@user_friendship = UserFriendship.request(current_user, @friend)
respond_to do |format|
if @user_friendship.new_record?
format.html do
flash[:error] = "There was a problem creating that friend request."
redirect_to user_path(@friend)
end
format.json {render json: @user_friendship.to_json, status: :precondition_failed}
else
format.html do
flash[:success] = "Friend request sent"
redirect_to user_path(@friend)
end
format.json {render json: @user_friendship.to_json, status: :precondition_failed}
end
end
else
flash[:error] = "Friend required"
redirect_to root_path
end
end
如果有人可以提供任何建议或反馈,那就太好了!
更新:
现在我添加了 data: _this.serialize()
并将 url 更改为: url: "/user_friendships"
我现在得到了一个 412(前提条件失败)
错误。尽管出现此错误,数据实际上已保存到数据库中。有谁知道为什么我会收到此 412(前提条件失败)
错误?
最佳答案
有件事我不明白,对于 dataType json,你说你有一个前提条件失败状态,对吗? 但你写了
format.json {渲染json:@user_friendship.to_json,状态::precondition_failed}
所以我认为没有任何问题,事实上,它似乎工作正常,因为您在渲染命令中显式传递了状态,请尝试将其删除,我认为您将获得 200(成功)状态。 当然,你可以保留之前的post ajax请求,或者使用这个简短的版本
$.post(
/user_friendships',
{ user_friendship: { friend_id: friendId } },
function(){
console.log(data);
friendButton.hide();
$(".friend-request-form").html("<p>Friend request sent</p>");
},
'json')
关于javascript - 我在 Rails 4 中使用 form_for 的 AJAX 请求做错了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22549852/