Rails 3: How to trigger a form submission via javascript?

后端 未结 5 1305
逝去的感伤
逝去的感伤 2020-12-30 08:25

I have a form that for the most part just submits as a normal form, so I don\'t want to set in the form_tag the :remote => true option.

However, under certain circum

5条回答
  •  北海茫月
    2020-12-30 09:15

    If you're using jQuery you could do something like this to have the form auto-post on keyup events, or simplify it to trigger manually:

      $(function() {    
        $("#live_search input").keyup(function() {
            q = $('#search_text').val();
          $.ajax({
              beforeSend      : function(request) { request.setRequestHeader("Accept", "text/javascript"); },
                               // Included so Rails responds via "format.js"
              data          : 'query=' + q,
              success       : function(data, textStatus, XMLHttpRequest) {
                                    // alert(textStatus);
                                    $("#live_search #results").html(data);
                                    },
              error         : function(XMLHttpRequest, textStatus, errorThrown) {
                                    // alert(errorThrown);
                                    $('#annotation_dialog').html(XMLHttpRequest.responseText);
                                    },
              type            : 'POST',
              url                 : '/search/live'
          });
          return false;
        });
    });
    

提交回复
热议问题