ป้ายกำกับ: AJAX

jQuery Ajax DebuggingjQuery Ajax Debugging

ข้อเสียอย่างหนึ่งเวลาใช้ Ajax คือ เวลามี error อะไร user จะไม่ทราบอะไรเลย เพราะว่าเป็นการโหลดแบบเบื้องหลัง บางทีโหลดเกือบจะเสร็จแล้ว แต่เห็นหน้านิ่ง ๆ เลย refresh ใหม่ซะเลย ความจริง jQuery มี event onErrors ไว้สำหรับจัดการเวลาใช้ Ajax แล้วมีปัญหาอยู่แล้ว แต่การที่จะต้องมาเขียนกำหนดให้ทุกตัวที่เรียกใช้ Ajax ก็ไม่สะดวกเลย จึงมี $.ajaxSetup ไว้ให้สามารถกำหนดคุณสมบัติที่เป็นส่วนกลางให้คำสั่ง Ajax ต่าง ๆ ทั้ง $.Ajax, $.get, $.json, $.post ใช้ร่วมกัน แค่ประกาศใช้ $.ajaxSetup เอาไว้ล่วงหน้า

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>jQuery.ajaxSetup</title>
</head>

<body>
<script src="assets/jQuery/jquery.min.js"></script>
<script>
$.ajaxSetup({
 "cache": false,
 "error": function(jqXHR, exception)
 {
  if(jqXHR.status === 0)
  {
   alert('Not connect.\n Verify Network.');
  }
  else if(jqXHR.status == 404)
  {
   alert('Requested page not found. [404]');
  }
  else if(jqXHR.status == 500)
  {
   alert('Internal Server Error [500].');
  }
  else if(exception === 'parsererror')
  {
   alert('Requested JSON parse failed.');
  }
  else if(exception === 'timeout')
  {
   alert('Time out error.');
  }
  else if(exception === 'abort')
  {
   alert('Ajax request aborted.');
  }
  else
  {
   alert('Uncaught Error.\n' + jqXHR.responseText);
  }
 },
 "scriptCharset": "utf-8",
 "timeout": 60000
});

$.post('nofile.php', function(data){
 alert(data);
});
</script>
</body>
</html>

เรื่องที่เกี่ยวข้อง