Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/79.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Jquery 通过AJAX和RAILS调用第二个方法_Jquery_Ruby On Rails_Ajax_Forms_Methods - Fatal编程技术网

Jquery 通过AJAX和RAILS调用第二个方法

Jquery 通过AJAX和RAILS调用第二个方法,jquery,ruby-on-rails,ajax,forms,methods,Jquery,Ruby On Rails,Ajax,Forms,Methods,我正在尝试使用ajax通过rails应用程序调用一个方法。我想知道是否有一种通过ajax检索信息的方法,无论该方法是成功通过还是调用另一个功能 $.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

我正在尝试使用ajax通过rails应用程序调用一个方法。我想知道是否有一种通过ajax检索信息的方法,无论该方法是成功通过还是调用另一个功能

$.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

我不太确定您想要完成什么,但一般来说,在Rails中处理Ajax请求的一种好方法是发回JavaScript,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
并创建相应的视图调用_sms.js.erb

<% if @sms.sent? %>
  alert("All is well!");
<% else %>
  alert("Something's wrong.");
<% end %>

警惕(“一切都很好!”);
警惕(“出了什么事。”);
一旦服务器的响应到达您的浏览器,就会弹出一个警报框


或者,您可以使用JSON对象进行响应,您可以在
$.ajax
函数的
success
回调中处理该对象。

由于未发送消息是一个已知错误,因此我将在success块中处理它。您可以将
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

我只是在看这个答案之前使用了这个方法,它按照我需要的方式工作。非常感谢。