jQuery .get错误响应功能? [英] jQuery .get error response function?
问题描述
多亏了StackOverflow,我设法使以下代码正常运行,但是我有一个后续问题.
Thanks to StackOverflow, I managed to get the following code working perfectly, but I have a follow up question.
$.get('http://example.com/page/2/', function(data){
$(data).find('#reviews .card').appendTo('#reviews');
});
上面的代码使我的网站能够使用WordPress中的加载更多"按钮来获取文章的第二页.但是,当网站页面/结果用完时,我遇到了一个小问题.加载更多按钮保持不变.即使没有剩余页面,它也会继续尝试获取数据.
This code above enabled my site to fetch a second page of articles with a Load More button in WordPress. However when the site runs out of pages/results, I'm running into a small issue. The load more button remains in place. It will keep trying to fetch data even if no pages are remaining.
如何调整此命令,以便在.get
请求失败或例如找不到(404)页面时显示视觉响应?
How can I tweak this command so that I can show a visual response if the .get
request fails or is a (404) not found page for instance?
如果有人可以通过一个简单的例子来帮助我,甚至是一个很棒的alert("woops!");
!
If someone could help me out with a simple example of even an alert("woops!");
that would be awesome!
谢谢!
推荐答案
$.get
没有给您设置错误处理程序的机会.您将需要使用低级 $.ajax
函数:
$.get
does not give you the opportunity to set an error handler. You will need to use the low-level $.ajax
function instead:
$.ajax({
url: 'http://example.com/page/2/',
type: 'GET',
success: function(data){
$(data).find('#reviews .card').appendTo('#reviews');
},
error: function(data) {
alert('woops!'); //or whatever
}
});
编辑10年3月
请注意,使用jQuery 1.5中新的 jqXHR
对象,您可以在调用$.get
之后设置错误处理程序:
Note that with the new jqXHR
object in jQuery 1.5, you can set an error handler after calling $.get
:
$.get('http://example.com/page/2/', function(data){
$(data).find('#reviews .card').appendTo('#reviews');
}).fail(function() {
alert('woops'); // or whatever
});
这篇关于jQuery .get错误响应功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!