为什么我的AJAX请求这么慢?

时间:2014-05-05 14:50:12

标签: javascript php jquery ajax

这个AJAX请求大约需要一秒钟才能执行,我想知道是否有办法加速它?

这是Twitter风格的关注/取消关注的上下文中的按钮点击事件。

JS:

$.ajax
({
    type: "POST",
    url: "follow.php",
    data: {id: id, shop_name: shop_name},
    context: this,
    success: function(data)
    {
        if ($(this).html() == 'Add')
        {
            $(this).toggleClass('btn-primary');
            $(this).html('<span class="glyphicon glyphicon-ok"></span> Added');
        }

        else if ($(this).html() == '<span class="glyphicon glyphicon-ok"></span> Added')
        {
            $(this).toggleClass('btn-primary');
            $(this).html('Add');
        }
    }
});

PHP:

ini_set('display_startup_errors',1);
ini_set('display_errors',1);
error_reporting(-1);

include('connect.php');

$id = $_POST['id'];
$user_id = $id['id'];
$shop_name = mysqli_escape_string($con, $_POST['shop_name']);

$feed_id_query = "SELECT DISTINCT feed_id FROM shopaholic WHERE shop_name = '$shop_name'";
$feed_id = mysqli_query($con, $feed_id_query) or die(mysqli_error($con));
$row = mysqli_fetch_array($feed_id);
$feed_id = $row[0];

$query = "SELECT * FROM sh_subscriptions WHERE user_id = $user_id AND feed_id = $feed_id";
$result = mysqli_query($con, $query) or die(mysqli_error($con));

// check if row exists
if (mysqli_num_rows($result) > 0)
{
    // row already exists, so check whether it is active
    $query2 = "SELECT * FROM sh_subscriptions WHERE user_id = $user_id AND feed_id = $feed_id AND active = 1";
    $result2 = mysqli_query($con, $query2) or die(mysqli_error($con));

    if (mysqli_num_rows($result2) > 0)
    {
        // row is active, so deactivate it
        $query3 = "UPDATE sh_subscriptions SET active = 0 WHERE user_id = $user_id AND feed_id = $feed_id";
        $result3 = mysqli_query($con, $query3) or die(mysqli_error($con));
    }

    else
    {
        // row is inactive, so activate it
        $query4 = "UPDATE sh_subscriptions SET active = 1 WHERE user_id = $user_id AND feed_id = $feed_id";
        $result4 = mysqli_query($con, $query4) or die(mysqli_error($con));
    }
}

else
{
    // row does not exist, so create it
    $query5 = "INSERT INTO sh_subscriptions (user_id, feed_id, active) VALUES ($user_id, $feed_id, 1)";
    $result5 = mysqli_query($con, $query5) or die(mysqli_error($con));
}

更新

我正在检查控制台中的AJAX加载时间。绝大多数时间花在'等待'上,我认为PHP正在做它的工作。它也会在第一次加载时变慢(至少比50ms慢50ms),然后通常变得更快。

1 个答案:

答案 0 :(得分:0)

您可以尝试的一件事是为两个选择添加“LIMIT 1”

$feed_id_query = "SELECT DISTINCT feed_id FROM shopaholic WHERE shop_name = '$shop_name' LIMIT 1";

$query = "SELECT * FROM sh_subscriptions WHERE user_id = $user_id AND feed_id = $feed_id LIMIT 1";

由于您在每个查询中只需要一个结果

同样在这里

$query2 = "SELECT * FROM sh_subscriptions WHERE user_id = $user_id AND feed_id = $feed_id AND active = 1 LIMIT 1";