programing

rails3 rails.js 및 jquery ajax 요청의 성공 및 실패 탐지

bestprogram 2023. 10. 19. 22:37

rails3 rails.js 및 jquery ajax 요청의 성공 및 실패 탐지

이전에는 레일 2.3.8에서 프로토타입 헬퍼를 사용했습니다.link_to_remote그리고.form_remote_for(기타 amongst).

이것들은 선택권이 있었습니다.:update다음과 같이

link_to_remote "Add to cart",
  :url => { :action => "add", :id => product.id },
  :update => { :success => "cart", :failure => "error" }

(설명서의 예).이 예제는 성공하면 HTML 요소를 클래스 "cart"로 업데이트하고 실패하면 클래스 "error"로 업데이트합니다.

이제 저는 modus operandi가 바뀌었다고 생각합니다. 대신 우리는 다음과 같이 적습니다.

link_to "Add to cart", :url => {:action => "add", :id => product.id}, 
    :remote => true

설정할 수 있는 옵션이 없습니다.:update더이상.일반 html 대신 jquery에서 다음과 같이 javascript를 렌더링합니다.

$('.cart').replaceWith(<%= escape_javascript(render :partial => 'cart') %>)

그러나 오류 상황을 어떻게 처리합니까?컨트롤러에서 처리하고 뷰를 별도로 사용합니까?

전에 했던 행동을 어떻게든 흉내 낼 수 있다는 것은 저에게 유용해 보입니다.무슨 생각 있어요?

하! 는 이 기사에서 그것이 묘사된 것을 발견했습니다.rails.js에서는 다음 콜백이 확인됩니다.

  • ajax:loading : Ajax 요청을 실행하기 전에 트리거됨
  • ajax: success : Ajax 요청이 성공한 후 트리거됨
  • ajax:complete : 응답 상태에 관계없이 Ajax 요청이 완료된 후 트리거됨
  • ajax:failure : ajax:success와 반대로 실패한 Ajax 요청 후 트리거됨

자바스크립트는 눈에 띄지 않아야 하므로 HTML에서 이 커플링이 이루어지지 않습니다.

(동일한 현장에서) 예: 다음 레일 2.3.8

<% form_remote_tag :url => { :action => 'run' },
        :id => "tool-form",
        :update => { :success => "response", :failure => "error" },
        :loading => "$('#loading').toggle()", :complete => "$('#loading').toggle()" %>

는 다음과 같이 번역됩니다.

<% form_tag url_for(:action => "run"), :id => "tool-form", :remote => true do %>

그리고 일부 javascript(application.js) 안에서, 당신은 이벤트들을 바인딩합니다.

jQuery(function($) {
  // create a convenient toggleLoading function
  var toggleLoading = function() { $("#loading").toggle() };

  $("#tool-form")
    .bind("ajax:loading",  toggleLoading)
    .bind("ajax:complete", toggleLoading)
    .bind("ajax:success", function(xhr, data, status) {
      $("#response").html(status);
    });
});

좋아요! :)

[업데이트: 29/12/2011]

최근에 이름이 바뀐 이벤트는 두 가지입니다.

  • ajax:beforeSend: 고인을 대신하다ajax:loading
  • ajax:error를 대체합니다.ajax:failure(jQuery 그 자체에 더 부합할 것 같습니다)

예를 들면 다음과 같습니다.

  $("#tool-form")
    .bind("ajax:beforeSend",  toggleLoading)
    .bind("ajax:complete", toggleLoading)
    .bind("ajax:success", function(xhr, data, status) {
      $("#response").html(status);
    });

완전성을 위해 이벤트와 예상되는 파라미터:

 .bind('ajax:beforeSend', function(xhr, settings) {})
 .bind('ajax:success',    function(xhr, data, status) {})
 .bind('ajax:complete', function(xhr, status) {})
 .bind('ajax:error', function(xhr, data, status) {})

관련 레일 4 가이드는 http://guides.rubyonrails.org/working_with_javascript_in_rails.html 에서 확인할 수 있습니다.

ncherro가 언급한 것처럼 https://github.com/rails/jquery-ujs/wiki/ajax 에 있는 이벤트 문서를 가리킵니다.

콜백에 전달된 실제 값은 jQuery의 값에서 유추할 수 있습니다.ajaxmethod http://api.jquery.com/jquery.ajax/ #jQuery-ajax-설정

.bind을 위해 감가상각됩니다..onjQuery: http://api.jquery.com/on/

이제 권장되는 접근 방식은 다음과 같습니다.

템플릿:

<%= link_to 'Click me!',
    'path/to/ajax',
    remote: true,
    id: 'button',
    method: :get,
    data: {type: 'text'}
%>

커피스크립트:

$(document).ready ->
  $("#button").on("ajax:success", (e, data, status, xhr) ->
    alert xhr.responseText
  ).on "ajax:error", (e, xhr, status, error) ->
    alert "error"

이 질문은 3년이 지난 것으로 알고 있지만, 구글 결과에서 높게 나오고 위에 나열된 이벤트 중 일부는 더 이상 사용되지 않습니다.

현재 목록은 여기를 참조하십시오 - https://github.com/rails/jquery-ujs/wiki/ajax

언급URL : https://stackoverflow.com/questions/3501317/rails3-rails-js-and-jquery-catching-success-and-failure-of-ajax-requests