如何在这个项目中改进PHP和JQuery代码-只淡出需要刷新的元素,而不是整个部分


How To Improve PHP and JQuery Code in this Project - only fade out elements that need refreshed instead of whole section?

我偶然发现了这个网站,对它印象深刻,并想尝试学习它是如何工作的:http://demo.pellegrom.me/uptime/

我的尝试是在这里:http://www.4playtheband.co.uk/up/up.php但我不得不淡出整个部分,而不仅仅是状态'。我的工具提示也坏了,因为它们是动态生成的-我确信我需要应用live函数,但不确定如何在不破坏它的情况下做到这一点。

代码如下:

up.php:

<?php
require('../db.php');
?>  
<script type="text/javascript">
$(document).ready(function(){
    $("#container").load("response.php").fadeIn("slow");
    setInterval(function() {
        $('#container').fadeOut('slow').load('response.php').fadeIn("slow");
    }, 3600000);
    $('.icon').each(function(){
        $(this).simpletip({
            showEffect: 'fade',
            hideEffect: 'fade',
            fixed: 'true',
            position: 'right',
            offset:[10, 0],
            content: $('img',this).attr('alt')
        });
    });
    $('#check').click(function(){
        $('.http-status').empty();
        $('.http-status').html('<img src="images/spinner.gif"/>');
        $('#container').fadeOut('slow').load('response.php').fadeIn("slow");
    });
});
</script>
<h2>Website Checker</h2>    
<div id="container"></div>
<br /> 
<a href="#" id="check" class="button">Check Now</a>

process.php:

<?php
require('../db.php');
function Visit($url)
{
    $agent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";$ch=curl_init();
    curl_setopt ($ch, CURLOPT_URL,$url );
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch,CURLOPT_VERBOSE,false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    $page=curl_exec($ch);
    //echo curl_error($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if($httpcode>=200 && $httpcode<300) 
    {
        echo '<span class="up">'.$httpcode.'<span class="icon"><img src="images/info.png" alt="website is up"/></span></span>';
    }
    else
    {
        $httpcode=404;
        echo '<span class="down">'.$httpcode.'<span class="icon"><img src="images/info.png" alt="website is down"/></span></span>';
        $date = date("l, j 'of F Y '@ H:i");
        $to      = "someone@domain.com";
        $subject = "Urgent: $url is down";
        $message = "Hello,'n'nIt appears that on our latest check of $url on $date that the site was down.'n'nRegards,'nWeb Checker";
        $headers = 'From: noreply@webchecker.co.uk' . "'r'n" .
               'Reply-To: noreply@webchecker.co.uk' . "'r'n";
        mail($to, $subject, $message, $headers);
    }
}
?>
<ul id="site-list" class="list"> 
    <li class="title">
        <span class="id"></span>
        <span class="name">Title</span>
        <span class="url">URL</span>
        <span class="status">HTTP Status</span>
    </li> 
<?php
// some PHP to fetch all the gig entries from the shows table
$sql = "SELECT * FROM `check`";
$query = mysql_query($sql) or die(mysql_error());
// a loop to place all the values in the appropriate table cells
while ($row = mysql_fetch_array($query)){
    //begin the loop...
    $id=$row['id'];
    $name=$row['name'];
    $url=$row['url'];
?>
    <li>
        <span class="id"><?php echo $id; ?></span>
        <span class="name"><?php echo $name; ?></span> 
        <span class="url"><?php echo $url; ?></span>
        <span class="status http-status"><?php echo Visit("$url"); ?></span>
    </li>
<?php
}
?>
</ul>

这是相当多的代码,如果它很难理解,请道歉。

除了已经提到的两点之外,唯一让我困惑的是,当container首次加载到正在访问的页面时,如何避免电子邮件发送?

提前感谢所有的帮助和建议。

自上次查看以来,我已经添加了Ajax,并对其他代码进行了一些修改。像php的返回和加载gif的html和ajax的其余部分。希望这对你有帮助!当你评论时,你应该包括'@'+'tumharyyaaden',以便stackexchange显示我更新,如果你有问题的话。

PHP: save as process.php

<?php
require('../db.php');
$url= NULL;
if(isset($_POST['a'])) {    $url = mysql_real_escape_string($_POST['a']);   }
function Visit($url)
{
    $agent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";$ch=curl_init();
    curl_setopt ($ch, CURLOPT_URL,$url );
    curl_setopt($ch, CURLOPT_USERAGENT, $agent);
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt ($ch,CURLOPT_VERBOSE,false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);
    $page=curl_exec($ch);
    //echo curl_error($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    if($httpcode>=200 && $httpcode<300) 
    {
        echo '<span class="up">'.$httpcode.'<span class="icon"><img src="images/info.png" alt="website is up"/></span></span>'; exit;
    }
    else
    {
        $httpcode=404;
        $date = date("l, j 'of F Y '@ H:i");
        $to      = "someone@domain.com";
        $subject = "Urgent: $url is down";
        $message = "Hello,'n'nIt appears that on our latest check of $url on $date that the site was down.'n'nRegards,'nWeb Checker";
        $headers = 'From: noreply@webchecker.co.uk' . "'r'n" .
               'Reply-To: noreply@webchecker.co.uk' . "'r'n";
        mail($to, $subject, $message, $headers);
        echo '<span class="down">'.$httpcode.'<span class="icon"><img src="images/info.png" alt="website is down"/></span></span>'; exit;
    }
}
if(!empty($url)){ Visit($url); exit; } 
?>
HTML:

<ul id="site-list" class="list"> 
    <li class="title">
        <span class="id"></span>
        <span class="name">Title</span>
        <span class="url">URL</span>
        <span class="status">HTTP Status</span>
    </li> 
<?php
// some PHP to fetch all the gig entries from the shows table
$sql = "SELECT * FROM `check`";
$query = mysql_query($sql) or die(mysql_error());
// a loop to place all the values in the appropriate table cells
while ($row = mysql_fetch_array($query)){
    //begin the loop...
    $id=$row['id'];
    $name=$row['name'];
    $url=$row['url'];
?>
    <li class="websites">
        <span class="id"><?php echo $id; ?></span>
        <span class="name"><?php echo $name; ?></span> 
        <span class="url"><?php echo $url; ?></span>
        <span class="status http-status"><img src="images/spinner.gif"/></span>
    </li>
<?php
}
?>
</ul>
<br /> 
<a href="#" id="check" class="button">Check Now</a>
jQuery:

$('#check').click(function(){
    $('.http-status').html('<img src="images/spinner.gif"/>');
    $('#site-list li.websites').each(function(){
        var newurl = $(this).find('span.url a').attr('href');
        $.ajax({
            type:    "POST",
            url:     "process.php",
            data:    ({"a":newurl}),
            cache:   false,
            success: function(message){
                $(this).find('li.status').html(message);
            } //End AJAX return
        }); //End AJAX call
    }); //End li each
}); //End Check
$('#check').click();

解释:对不起,我没有注释代码,但基本上,三个部分,两个php的一个将生成html,一个将检查并返回状态,最后一个是JS,它将通过AJAX发送请求,所以你的页面不必刷新每次检查点击。

更新:2011/08/25

对我来说似乎很奇怪,你当前的代码(即JS)不像我提供的任何东西。我上面有你的页面的整个结构。所以我会说考虑至少采用上面的JS并修改它以适应您的其他需求,而不是试图修复您当前的代码,我想说它有太多的错误。无论如何,让我们看看你的代码:

代码

$('#check').click(function(){
    $('#site-list li').each(function(){
        var li=$(this);
        if(!li.hasClass('title'))
        {
            $('span.status',li).html('<img src="images/loader.gif" alt="" />');
            $.post('process.php',{
            url:$('span.url',li).text(),
            id:$('span.id',li).text()},
            function(response)
            {
                $('span.status',li).html(response.data);
                $('span.status',li).simpletip({fixed:true,position:'right',offset:[5,0],content:response.message});
                var tooltip=$('span.up',li).eq(0).simpletip();
                if(response.up){
                    $('span.up img',li).attr('src','images/activity_monitor.png');
                    tooltip.update('Site is Up');}
                else{
                    $('span.up img',li).attr('src','images/activity_monitor_warning.png');tooltip.update('Site is Down');$('span.status span',li).css('color','red');
                }
            },'json');
        }
    });
    return false;
});

所以,首先,1).你错过了$('#check').click();,它目前阻止加载或状态在页面加载时正确显示。也就是说,这段代码对你来说不是可选的。

第二个2).你的选择器和选择过程非常低效。

$('#site-list li').each(function(){
        var li=$(this);
        if(!li.hasClass('title'))
        {

上面,你的第一个选择器应该是$('#site-list li.websites').each(,这样你就不需要在标题类列表上运行不必要的检查,也不必在排除整个列表的标题类时单独运行第二次检查。当在each()下做这些低效的检查时,它会导致许多不应该进行的不必要的调用。

通过使用选择器样式、工具提示插件的选择以及使用.post而不是.ajax,您不必要地使脚本复杂化。对于tooltip,使用像tiptip tooltip这样的东西,它重量轻,非常容易使用,但可定制,功能丰富,将极大地简化您的脚本。ajax更干净,更透明,更容易,因此减少了潜在的冲突。另外,使用实际的CSS样式和属性来格式化文档,而不是使用JS。所以,我喜欢代码更干净,更简单,更透明,最重要的是,更高效,所以,如果你需要帮助来定制我的代码以满足你的需求,我可以帮助你。但是根据你现在的代码,我不能说哪一部分是错的,因为我觉得太多了。

Forth 4).我无意冒犯你,但我个人无法忍受当前JS代码的方式。所以请不要往心里去,这只是个人喜好的问题。也就是说,我可以帮助你修改我原来的答案,以更好地满足你的需求。