On success, I would like to show different values depending on what value exists. For example, if $('#add').val() has a value in it I would like to show 'Video added" as part of the success function. If $('#remove').val() has a value in it, I would like to show 'Video removed' as part of the success function. Either #add or #remove will have a value in it at a given time. How do I enable this?
<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>' )
if just checking text is enough you can use this code:
<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>
I assumed #add
or #remove
are text. The key is this if
check:
if ( $('#add').text() ) {
//... add is not empty because there is some text in it...
If #add
or #remove
may contain text or any other element, you can check them with :empty
selector:
if ( !$('#add:empty').length ) {
//... #add is not empty so something was added successfully ...
If #add
or #remove
are <input>
elements like text box you can do the same check with:
if ( $('#add').val() ) {
//... add is not empty ...
I like to return a response when the backend script has executed, XML would look something like this
<status>true</status>
<successMessage>Video deleted</successMessage>
or
<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();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.