簡體   English   中英

如何使用jQuery / Ajax基於變量更改成功函數的輸出?

[英]How do I change the output of the success function based on a variable using jQuery/Ajax?

成功之后,我想根據存在的值顯示不同的值。 例如,如果$('#add')。val()中有一個值,我想在成功函數中顯示“已添加視頻”。如果$('#remove')。val()中有一個值中,我想在成功功能中顯示“已刪除視頻”。在給定的時間#add或#remove都將具有值。如何啟用此功能?

<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>

如果確定只有一個文本字段具有值,則可以執行以下操作:

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

如果僅檢查文本就可以使用以下代碼:

<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').text() ) {
   //... add is not empty because there is some text in it...

如果#add#remove可能包含文本或任何其他元素,則可以使用:empty選擇器檢查它們:

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

如果#add#remove<input>元素(例如文本框),則可以使用以下方法進行相同的檢查:

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

我想在后端腳本執行后返回響應,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();
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM