0

I want to create a code that reloads a part of the page every 10 seconds and if it fails to reload (because of connection issue), then it plays a sound.

Is such thing possible using ajax and how? I have seen this type of feature in web chats before but never came across a code for it.

4

2 回答 2

2

尝试使用 setInterval 函数:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=windows-1250">
        <title>Test</title>
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" type="text/css">
        <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript" language="JavaScript"></script>
        <style type="text/css">
        <!--
          .square {
              background-color: #AAAAAA;
              width: 250px;
              height: 100px;
          }
        //-->
        </style>
<script type="text/javascript" language="JavaScript">
  $(document).on('ready',function(){
    setInterval(updateDiv,10000);
  });

  function updateDiv(){
    $.ajax({
      url: 'getContent.php',
      success: function(data){
        $('.square').html(data);
      },
      error: function(){
        //Code to play a sound
        $('.square').html('<span style="color:red">Connection problems</span>');
      }
    });
  }
</script>
</head>
<body>
  <h1>The next div will be updated every 10 seconds</h1>
  <div class="square">
    Hello
  </div>
</body>
</html>

和 php 脚本:

<?php
  echo "Updated value --> " . rand();
?>

要测试,请尝试重命名 php 脚本(模拟连接问题)并重命名为原始名称(getContent.php)以再次测试正确的情况。希望这可以帮助。

于 2013-05-08T01:28:48.040 回答
1

使用 JQuery,您可以添加处理程序以在失败时运行...

$.ajax({
  dataType: "json",
  url: "myurl.com"
}).done(function( data ) {
    //do what you want when it's all good
}).fail(function() {
    //do what you want when the call fails
});

或者你可以这样做......

$.ajax({
    type: "post", 
    url: "/SomeController/SomeAction",
    success: function (data, text) {
        //do what you want when it's all good
    },
    error: function (request, status, error) {
         //do what you want when the call fails
    }
});

对于每个请求,这里是一个jsfiddle,它每 2 秒调用一次服务,或者使用将返回日期的 URL,或者使用将失败的错误 URL,模仿失败的服务器。

更新:我修改了 jsfiddle 以播放声音,只要该声音保留在它所在的服务器上:)

于 2013-05-08T00:54:42.083 回答