我有一个从发出 HTTP GET 请求的按钮调用的 Javascript。当它遇到错误时,它会显示一个带有请求错误的隐藏 div,这一切都运行良好。这是脚本:
$("#callContact1").click(function() {
console.log('starting event');
$.ajax({
url: "<?php echo $eventURL ;?>" + eventID + "<?php echo $eventURL ;?>",
data: {},
type: "GET"
})
.then(function(data, status, xhr) {
$('#ajaxResponse1').html(data).show();
var httpStatus = status;
var httpResponseCode = (xhr.status);
console.log('httpStatus: ' + httpStatus);
console.log('httpResponseCode: ' + httpResponseCode);
})
.fail(function(xhr) {
var httpStatus = (xhr.status);
var httpResponseCode = (xhr.getAllResponseHeaders);
var ajaxError = 'There was an requesting the event. HTTP Status: ' + httpStatus;
console.log('httpStatus: ' + httpStatus);
console.log('httpResponseCode: ' + httpResponseCode);
//make alert visible
$('#ajaxResponse1').html(ajaxError).show();
})
})
我现在需要稍微扩展一下,当成功时,显示一个不同的隐藏 div 和成功消息,例如:
$('#ajaxResponseSuccess1').html('Event Update in Progress').show();
我只是不确定如何扩展这个脚本——此时对于 JS 和 jQuery 来说还是相当新的。
最佳答案
JQuery AJAX中有一个成功函数:
像这样使用它:
.success(function(response) {
//DO stuff here.
})
更好更简单的代码可以是这样的:
$.ajax({
url: 'http://example.com',
method: 'GET',
success: function (response) {
},
error: function (e) {
}
});
查看 JQuery ajax 函数的完整文档位于 http://api.jquery.com/jquery.ajax/
或在
关于Javascript AJAX 请求 - 检查操作是否成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44559969/