2010-08-03 3 views
2

조심스럽게 조심성있는 j를 구현하는 방법 (Rails & jQuery를 사용하여) 양식을 포함하는 새로운 내용을 .load (ing) 한 후 제출 버튼/양식..load (ed) 폼에 버튼/폼을 제출하는 방법 (re) bind

내가 (사용자가 생성 버튼을 클릭 할 때) 항목의 lising의 상단에 보여주는 '새 항목을 만들'양식을 설정 한

sale_case/쇼/_requirments_new.html.haml :

- form_for ([@sale_case, @sale_case_requirement]), :html => { :id => 'requirement_form', :class => "submit-with-ajax"} do |f| 
... 
%button{ :type => "submit" } Save Requirement 

application.js :

jQuery(document).ready(function() { 
    jQuery(".submit-with-ajax").submitWithAjax(); 
} 
... 
jQuery.ajaxSetup({ 
    'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")} 
}) 

jQuery.fn.submitWithAjax = function() { 
    this.submit(function() { 
    jQuery.post(this.action, jQuery(this).serialize(), null, "script"); 
    return false; 
    }) 
    return this; 
}; 

requirements_controller.rb :

def create 
    @sale_case_requirement = @sale_case.requirements.new(params[:requirement]) 
     if @sale_case_requirement.save 
     @message = "Success..." 
     @success = true 
    #... 
    respond_to do |format| 
    format.js 
    end 
end 

요구 사항/create.js.erb : 그것은 모든 주위에 눈에 띄지 않게 잘 처음으로 일하고

mesg("<%= @message %>"); 
<%- if @success %> 
    jQuery("#requirement_form")[0].reset(); 
    jQuery('#requirements').load('<%= requirements_view_sale_case_requirements_path(@sale_case.id) %>'); 
<% end %> 

. 이 문제는 사용자가 두 번째 항목 (ajax를 통해로드 된 양식에 있음)을 작성할 때 발생합니다. 버튼이 submitWithAjax 함수에 바인딩되지 않습니다. 콘텐츠를로드 할 때 어떻게합니까?

부분적으로 (눈에 잘 띄지 않게)이 작업을 수행하기 위해이 작업을 수행해야했지만 결국이 작업을 이해할 수없는 버그가 발생했습니다. :

%button{ :type => "submit", :onclick => "jQuery.post('#{sale_case_requirements_path(@sale_case.id, @sale_case_requirement.id)}', jQuery('#requirement_form').serialize(), null, 'script'); return false;"} Save Requirement 

답변

1

변경이 원래 코드 : 이것에

jQuery(document).ready(function() { 
    jQuery(".submit-with-ajax").submitWithAjax(); 
} 

:

jQuery(document).ready(function() { 
    jQuery(".submit-with-ajax").live('submit', submitWithAjax); 
} 

이 원래 코드 : 이것에

jQuery.fn.submitWithAjax = function() { 
    this.submit(function() { 
    jQuery.post(this.action, jQuery(this).serialize(), null, "script"); 
    return false; 
    }) 
    return this; 
}; 

:

jQuery.fn.submitWithAjax = function() { 
    jQuery.post(this.action, jQuery(this).serialize(), null, "script"); 
    return false; 
}; 

jQuery .live() 호출은 지정된 선택기와 일치하는 현재 및 미래의 모든 요소에서 명명 된 처리기를 명명 된 이벤트에 바인딩합니다. 여기에는 ajax를 통해로드되는 요소가 포함됩니다. 다행히 그게 당신이 찾고있는 것입니다. http://api.jquery.com/live/

+0

굉장합니다. 시간 내 주셔서 정말 고마워요.(나는 스택 오버플로에서 많은 것을 얻었으며, 최근 참여를 도우려는 노력을하고 있습니다.) 내가 가진 문제와 내가 마침내 한 것에 대한 답을보십시오. –

1

가 여기에 내가 청산의 입력에 따라 코드에서 변경 끝났다 내용은 다음과 같습니다

는하여 .live() 함수에 문서에 대해 다음을 참조하십시오.

jQuery(document).ready(function() { 

    # Just put it all in one place 
    jQuery(".submit-with-ajax").live('submit', function() { 
     jQuery.post(this.action, jQuery(this).serialize(), null, "script"); 
     return false; 
     }); 
... 
} 
를 application.js : 나는 어떤 작품이 함께했다 나는 코드의 자신의 버전으로 'submitWithAjax'을 찾는 오류를 얻었으나, 그가 올바른 방향과 .live 문서를 읽은 후 나에게 지적

sale_case/쇼/_requirments_new.html.haml :

# Change the button back to unobtrusive 
%button{ :type => "submit"} Save Requirement  

감사합니다!

+0

예, 리뷰를 통해 .live() 호출에서 함수 이름 다음에 괄호를 사용하면 발생했던 오류가 발생했음을 확신합니다. – Ender