我有一个简单的AJAX请求,它根据表中的一些选择更新一些PHP会话变量。当用户做出选择时,它会触发一个AJAX请求。目前,如果AJAX请求出现错误,我将通过显示隐藏的Bootstrap Alert
显示通用错误消息<div id="alert_ajax_error" class="alert alert-danger text-center" role="alert" style="display:none">
There was an error updating your selections - please contact the Support Desk
</div>
我现在想改变一般的错误消息(有一个错误更新您的选择-请联系支持台),以显示从AJAX请求返回的错误字符串。
下面是我的脚本:
$(document).ready(function() {
$('button.btn-success').click(function() {
var itemID = $(this).closest('tr').attr('id');
console.log(itemID);
// Create a reference to $(this) here:
$this = $(this);
$.post('updateSelections.php', {
itemID: itemID,
selectionType: 'yes'
}, function(data) {
data = JSON.parse(data);
if (data.error) {
var ajaxError = (data.text);
console.log(ajaxError);
console.log('something was wrong with the ajax request');
$this.closest('tr').addClass("warning");
//make alert visible
$("#alert_ajax_error").show();
return; // stop executing this function any further
} else {
console.log('update successful - success add class to table row');
$this.closest('tr').addClass("success");
$this.closest('tr').removeClass("danger");
//$(this).closest('tr').attr('class','success');
}
}).fail(function(xhr) {
console.log('ajax request failed');
// no data available in this context
$this.closest('tr').addClass("warning");
//make alert visible
$("#alert_ajax_error").show();
});
});
});
ajaxError变量包含我想在我的警报中使用的字符串。是否有可能以某种方式使用它并将其插入显示的警报中?
你可以通过:
$('#alert_ajax_error').html(data);