gpt4 book ai didi

javascript - 无法使用 Ajax 接收 Rails 响应

转载 作者:太空宇宙 更新时间:2023-11-03 16:30:08 26 4
gpt4 key购买 nike

当我从 phonegap(使用 ajax,在 javascript 中)向我的 Rails 服务器发布内容时,发布成功,但我的服务器没有响应,所以最终失败了。我不明白为什么我得不到回应..

例如,这是我的注册脚本(带有 ajax 的 javascript):

$('#sign-up-button').click(function(e) {
var str = $("#signUpForm").serialize();
$(".error").remove();
e.preventDefault();
$.ajax({url: "http://localhost:3000/api/users.json",
type: "POST",
data: str,
success: function(result, status) {
alert('success');
$.mobile.changePage( "welcome.html", { transition: "slide"} );
},
error: function(result) {
alert('error');
}
});
});

还有我在 Ruby on rails 端的代码:

 # POST /users
# POST /users.json
def create
@user = User.new(params[:user])

respond_to do |format|
if @user.save
format.html { redirect_to @user, notice: 'User was successfully created.' }
format.json { render json: @user, status: :created }
else
format.html { render action: "new" }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end

在 firebug 中,我有:消息 201 Created,用户已创建(我可以检查它),但我没有响应,所以出现消息 alert('error') ...

非常感谢您的建议!

最佳答案

如果您期待一个空响应,例如 201,您需要在 $.ajax 选项中指定 dataType: 'text'。现在发生的事情是 jQuery 试图将响应解析为 JSON,但由于没有解析响应而失败。

关于javascript - 无法使用 Ajax 接收 Rails 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17606723/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com