jQuery如何使用ajaxError()方法?代码示例

2021年3月26日17:05:58 发表评论 639 次浏览

ajaxError()方法jQuery中的ins用于指定AJAX请求失败时要运行的函数。

语法如下:

$(document).ajaxError( function(event, xhr, options, exc) )

参数::此方法接受强制性的单参数功能。此函数接受以下列出的四个参数:

  • 事件:此参数保存事件对象。
  • xhr:它包含XMLHttpRequest对象。
  • 选项:它包含AJAX请求中使用的选项。
  • 排除:它包含JavaScript异常。

存储在服务器上的demo.txt文件, 单击该文件后将加载

改变内容

按钮。

demo.txt

This is GFG.

范例1:本示例通过从服务器获取数据来更改<p>元素的内容。当AJAX请求由于错误而失败时, 页面会显示AJAX请求失败。.

<!DOCTYPE html> 
< html > 
     < head > 
         < script src = 
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" > 
         </ script > 
          
         <!-- Script to use ajaxError() method -->
         < script > 
             $(document).ready(function() {
                 $(document).ajaxError(function() {
                     alert("AJAX request fails.");
                 });
              
                 $("button").click(function() {
                     $("#paragraph").load("demo.txt");
                 });
             });
         </ script > 
     </ head > 
      
     < body style = "text-align:center;" > 
      
         < div id = "div_content" > 
          
             < h1 style = "color: green;" >
                 lsbin
             </ h1 > 
              
             < p id = "paragraph" style = "font-size: 20px;" >
                 A computer science portal for geeks
             </ p > 
         </ div > 
          
         < button >
             Change Content
         </ button > 
     </ body > 
</ html >

输出如下:

在单击按钮之前:

jQuery如何使用ajaxError()方法?代码示例1

单击按钮后:

jQuery如何使用ajaxError()方法?代码示例2

范例2:本示例通过从服务器获取数据来更改<h1>元素的内容。当AJAX请求由于错误而失败时, 页面会显示AJAX请求失败。.

<!DOCTYPE html> 
< html > 
     < head > 
         < script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js" > 
         </ script > 
          
         <!-- Script to use ajaxError() method -->
         < script > 
             $(document).ready(function() {
                 $(document).ajaxError(function() {
                     alert("AJAX request fails.");
                 });
              
                 $("button").click(function() {
                     $("#heading").load("demo.txt");
                 });
             });
         </ script > 
     </ head > 
      
     < body style = "text-align:center;" > 
      
         < div id = "div_content" > 
          
             < h1 id = "heading" style = "color: green;" >
                 lsbin
             </ h1 > 
              
             < p style = "font-size: 20px;" >
                 A computer science portal for geeks
             </ p > 
         </ div > 
          
         < button >
             Change Content
         </ button > 
     </ body > 
</ html >

输出如下:

在单击按钮之前:

jQuery如何使用ajaxError()方法?代码示例3

单击按钮后:

jQuery如何使用ajaxError()方法?代码示例4

木子山

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: