2017-10-18 43 views
-1

這是我的代碼:Ruby on Rails的:AJAX和提交申請運行部件並聯

<%= simple_form_for @video do |form| %> 
    <div class="form-inputs"> 
    <%= form.input :title, id: :video_title %> 
    <div class="row"> 
     <div class="input-field col s12"> 
      <textarea id="textarea1" name="video[description]" class="materialize-textarea"></textarea> 
     <label for="textarea1">Description</label> 
    </div> 
    </div> 
    <label for="spaceTags">Tags</label> 
    <div id="spaceTags" class="chips chips-placeholder"></div> 
    <%= form.label :movie %> 
    <%= form.file_field :movie %> 
    <%= form.label :preview_images%> 
    <%= form.file_field :preview_images, multiple: true %> 
    <p> 
    <input type="checkbox" name=video[published] id="test5" /> 
    <label for="test5">Publish Video</label> 
</p> 
<div class="form-actions" onclick="fetch();"> 
    <%= form.submit%> 
</div> 
<% end %> 

和我的JavaScript代碼是:

$('#textarea1').trigger('autoresize'); 
$('.chips').material_chip(); 
$('.chips-placeholder').material_chip({ 
    placeholder: 'Enter a tag', 
    secondaryPlaceholder: '+Tag', 
}); 
function fetch(){ 
var x = $('#spaceTags').material_chip('data'); 
$.ajax({ 
    type: "POST", 
    url : "/videos", 
    data: {"sarthak":JSON.stringify(x)}, 
    success : function(){alert ("Success!")}, 
    error : function(data){alert(data.message)} 
    }); 
    } 

當我嘗試提交表單它使調用在這兩種情況下同樣的行爲。有什麼方法可以延緩表單提交,直到AJAX調用被執行或者我可以通過其他方式解決這個問題。

+1

壞命名你的函數'fetch' ...它已經存在於全局範圍內......你要麼覆蓋它,要麼阻止在範圍內使用它。應該命名一些:'getVideos'調用一個獲取函數可以獲取任何東西,如果你只看代碼 – Endless

回答

0

您可以使用event.preventDefault這將停止窗體的正常執行,只是觸發您的fetch方法。

您可以fetch方法更改爲:

function fetch(event){ 
    event.preventDefault(); 
    // the rest of your code 
} 

然後,在你的Ajax success的諾言,你可以處理其他任何你想要的,甚至再次提交表單,如果你想

$.ajax({ 
    type: "POST", 
    url : "/videos", 
    data: {"sarthak":JSON.stringify(x)}, 
    success : function(){ 
     alert ("Success!"); 
     $('form').submit() 
    }, 
    error : function(data){alert(data.message)} 
    });