我正在尝试使用ajax通过我的rails应用程序调用方法。我想知道是否有办法通过ajax检索信息是否成功通过或调用另一个fumction。
$.ajax({
type: "GET/POST", // which ever will be better
url: "",
success: function(form) {
//something i can put here to call a method in rails to retrieve variables from rails
},
error: function() {
//some code
}
});
我需要对控制器做些什么才能让它发挥作用?
def call_sms
@text_number = params[:phone_number]
@text_message = params[:text_message].to_s
@sms = ShortMessagingService.new
if @sms.send(@text_number, @text_message)
@sms_message = @sms.sent?
respond_to do |format|
format.js {render :nothing => true}
end
else
false
end
end
答案 0 :(得分:1)
我不确定你要完成什么,但一般来说,在Rails中处理Ajax请求的一种好方法是发回JavaScript,这是在到达时执行的。例如,如果您将控制器更改为:
def call_sms
@text_number = params[:phone_number]
@text_message = params[:text_message].to_s
@sms = ShortMessagingService.new
@sms.send(@text_number, @text_message)
respond_to do |format|
format.js
end
end
并创建相应的视图call_sms.js.erb
<% if @sms.sent? %>
alert("All is well!");
<% else %>
alert("Something's wrong.");
<% end %>
一旦服务器的响应进入您的浏览器,就会弹出一个警告框。
或者,您可以使用success
$.ajax
函数回调中处理的JSON对象进行响应。
答案 1 :(得分:0)
由于未发送消息是已知错误,我将在成功块中处理它。您可以将json
对象从服务器传递到客户端并将变量放入其中。在这里,如果短信成功发送,我将发送true
消息。
$.ajax({
type: "GET/POST", // which ever will be better
url: "",
success: function(data) {
if (data.message == "true"){
//message sent
} else{
//message was not send
}
},
error: function() {
// handle if ajax request fails for unknown reasons
}
});
def call_sms
@text_number = params[:phone_number]
@text_message = params[:text_message].to_s
@sms = ShortMessagingService.new
@sms.send(@text_number, @text_message)
@sms_message = @sms.sent?
respond_to do |format|
# you can pass other variables the same way as message
format.js {render :json => {:message => @sms_message}}
end
end