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

发布于 2024-12-01 00:59:22 字数 4344 浏览 3 评论 0原文

我偶然发现了这个网站,并对它印象深刻,并想尝试了解它是如何工作的: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      = "[email protected]";
        $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: [email protected]' . "\r\n" .
               'Reply-To: [email protected]' . "\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 时发送电子邮件?

预先感谢所有帮助和建议。

I came across this website and was impressed by it and wanted to try and learn how it works: http://demo.pellegrom.me/uptime/

My attempt is here: http://www.4playtheband.co.uk/up/up.php but I have had to fade out the entire section rather than just the status'. My tooltips are also broken because they are dynamically generated - I'm sure I need to apply the live function but just not sure on how to do this without breaking it.

Here is the code:

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      = "[email protected]";
        $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: [email protected]' . "\r\n" .
               'Reply-To: [email protected]' . "\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>

That's quite a lot of code, apologies if it's difficult to follow.

Aside from the two points already mentioned, the only other thing puzzling me is how to avoid the e-mail sending when container is first loaded upon the page being visited?

Thanks in advance for all help and suggestions.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光磨忆 2024-12-08 00:59:22

自从您上次查看以来,我添加了 Ajax,并稍微修改了其他代码。就像 php 中的 return 和为 html 加载 gif 以及 ajax 的其余部分一样。希望这有帮助!当您发表评论时,您应该包含“@”+“tumharyyaaden”,以便 stackexchange 向我显示更新(如果您有疑问)。

PHP: 另存为 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      = "[email protected]";
        $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: [email protected]' . "\r\n" .
               'Reply-To: [email protected]' . "\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,一个将检查并返回状态,最后一个bit 是 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,您不必要地使脚本变得复杂。对于工具提示,请使用诸如tiptip工具提示之类的东西,它重量轻,非常易于使用但可定制,功能齐全,并且将极大地简化您的脚本。 .ajax 更干净、更透明、更容易,因此减少了冲突的可能性。另外,使用实际的 CSS 样式和属性来格式化文档,而不是 JS。再说一遍,我喜欢更干净、更简单、更透明的代码,最重要的是,更高效,所以再说一遍,如果您需要帮助根据您的需求定制我的代码,我可以提供帮助。但就您目前的代码而言,我不能说哪一部分是错误的,因为对我来说太多似乎是错误的。

第四 4).我无意粗鲁或冒犯您,但就我个人而言,我无法忍受当前 JS 代码的方式。所以请不要认为这是针对个人的,这只是偏好问题而不是其他任何事情。也就是说,我可以帮助您更改我原来的答案,以更好地满足您的需求。

I have added the Ajax since you last looked at, as well as modify other code a little. Like returns in php and loading gif for html and rest of ajax. Hope this helps! when you comment, you should include '@'+'tumharyyaaden' so that stackexchange shows me update, if you have questions ofc.

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      = "[email protected]";
        $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: [email protected]' . "\r\n" .
               'Reply-To: [email protected]' . "\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();

Explanation: Sorry i didn't get to comment the code, but basically, three pieces to it, two php's one that will generate the html, one that will check and return status and last bit is JS which will send requests via AJAX so your page doesn't have to refresh on every check click.

UPDATE: 2011/08/25

It seems odd to me that your current code (namely JS) doesn't resemble anything of what i provided. What i have above is entire construct of your page. So i would say consider adopting at least the JS from above and modifying it to fit your other needs rather than to try and fix your current code which i would say has too many things wrong with it. Anyhow, lets look at your code:

Your code

$('#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;
});

So, first, 1). you are missing the $('#check').click(); which currently prevents loading or the status from showing up properly on page load. Meaning, that bit of code is not optional for you.

Second 2). Your selectors and process of selecting are very inefficient.

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

Above, your first selector should have been $('#site-list li.websites').each( so you wouldn't need to run unnecessary checks on Title class list nor will have to run second check separately on excluding the title class for entire list. When doing these sorts of inefficient checks under each() it causes so many unnecessary calls that shouldn't made.

Third 3). You are unnecessarily complicating the script by using your selector style, choice of tooltip plug-in and by using .post instead of .ajax. For tooltip, use something like tiptip tooltip, it's light weight, very easy to use but customizable, full of features and will vastly simplify your script. .ajax is cleaner, more transparent and easier hence reduces potential for conflicts. Also, use actual CSS styles and properties for formatting document, not JS. So again, I like the code that's cleaner, simpler, more transparent and most of all, more efficient, so again, if you need help customizing my code to your needs, i can help. But as your code currently stands, i can not say which part is wrong since too much seems wrong to me.

Forth 4). I don't mean to be rude or to offend you but personally i can not stand the way the current JS code stands. So please don't take this personally, it's just matter of preference more than anything else. That said, i can help you in changing my original answer to better suit your needs.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文