2012-11-20 34 views
2

成功後,我想根據存在的值顯示不同的值。例如,如果$('#add')。val()中有一個值,我想顯示'Video added'作爲成功函數的一部分。如果$('#remove')。val()在它的價值,我想顯示「視頻清除」作爲成功的部分功能。無論是#將或#remove將在給定時間有一個值,如何啓用這個?如何根據使用jQuery/Ajax的變量更改成功函數的輸出?

<script type="text/javascript"> 
    $(document).ready(function() { 
     $("#test").submit(function(event){ 
     event.preventDefault(); 
      $.ajax({ 
       type:"POST", 
       url:"/edit_favorites/", 
       data: { 
         'video_add': $('#add').val(), // from form 
         'video_remove': $('#remove').val() // from form 
         }, 
       success: function(){ 
        $('#message').html("<h2>Video added!</h2>") 
        } 
      }); 
      return false; 
     }); 

    }); 
</script> 

回答

4

如果你確信只有文本框之一將有一個值,你可以做這樣的事情:

$('#message').html('<h2>' + $('#add').val() !== '' ? 'Video added' : 'Video removed' + '!</h2>') 
+0

感謝約翰。我如何解釋此聲明?我正在考慮使用if/else語句來執行此操作。 – sharataka

+0

@sharataka沒問題。它實際上是if的短手版本。我試圖詳細說明:(布爾)?/*如果bool爲true,則執行操作* /:/ *將它填充爲false * /。 '$('#add')。val()!=='''會評估爲true或false,取決於它是否有值 – Johan

0

如果只檢查文本是的話,你可以使用此代碼:

<script type="text/javascript"> 
    $(document).ready(function() { 
     $("#test").submit(function(event){ 
     event.preventDefault(); 
      $.ajax({ 
       type:"POST", 
       url:"/edit_favorites/", 
       data: { 
         'video_add': $('#add').val(), // from form 
         'video_remove': $('#remove').val() // from form 
         }, 
       success: function(){ 
        if ($('#add').text()) { 
         $('#message').html("<h2>Video added!</h2>"); 
        } else if ($('#add').text()){ 
         $('#message').html("<h2>Video removed!</h2>"); 
        } else { 
         $('#message').html("<h2>Wasn't either add or remove!</h2>"); 
        } 
        } 
      }); 
      return false; 
     }); 

    }); 
</script> 

我假設#add#remove是文字。最關鍵的是這個if檢查:

if (!$('#add:empty').length) { 
    //... #add is not empty so something was added successfully ... 

如果#add#remove<input>元素,如文本:

if ($('#add').text()) { 
    //... add is not empty because there is some text in it... 

如果#add#remove可以包含文本或任何其他元素,你可以用:empty選擇檢查它們盒子可以做同樣的檢查:

if ($('#add').val()) { 
    //... add is not empty ... 
0

我喜歡後端腳本執行時返回響應,XML會是這個樣子

<status>true</status> 
<successMessage>Video deleted</successMessage> 

<status>false</status> 
<errorMessage>Video not found on the server</errorMessage> 

的Javascript

success: function (response) { 
    if($(response).find("status").text()=="true"){ 
     $(".success").html($(response).find("successMessage").text()); 
     $(".success").show(); 
    }else{ 
     $(".error").html($(response).find("errorMessage").text()); 
     $(".error").show(); 
    } 
} 
相關問題