ajax成功的If /else语句

if/else statement on ajax success

本文关键字:else 语句 If 成功 ajax      更新时间:2023-09-26

我试图获得未读消息的计数器:php代码(BubbleStat.php)如下所示:

$totalMsg = $mysql->totalRows("SELECT msg_id from messages WHERE msg_opened = 0 AND msg_receiver = '".$_SESSION["ActiveUserSessionId"]."'");
    echo $totalMsgs;

jQuery代码如下:

$.ajax({
type: "POST",
url: '/BubbleStat.php',
cache: false,
success: function(html)
    {
        $("#Bubble_Msg").show(); 
    } 
});

所以我怎么能得到计数器的未读消息在#Bubble_Msg ?如果计数器没有未读消息来隐藏div #Bubble_Msg,那就太好了。

任何想法?

试试这个:

success: function(html) {
    // Check if the Counter have unread messages
    if (parseInt(html) > 0) {
        $("#Bubble_Msg").text(html).show();
    }
    else {
        $("#Bubble_Msg").hide();
    }
}​

As in….text() ?

$("#Bubble_Msg").text(html).show();

如果html命名的变量实际上包含HTML,那么….html()

这样使用:

success: function(html)
{
    $("#Bubble_Msg").html(html).show(); 
} //-----------------------^^----------this html is the param passed in the 
  //-----------------------------------success function

可以让PHP脚本返回JSON响应。

这可能看起来像很多代码,但绝对值得如果你需要增加复杂性到你的脚本。

1-确保无论发生什么情况,响应都不会被缓存:

header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');

2- json类型报头:

header('Content-type: application/json');

3-计算你需要知道的每一个值:

$totalMsg = $mysql->totalRows("SELECT msg_id from messages WHERE msg_opened = 0 AND msg_receiver = '".$_SESSION["ActiveUserSessionId"]."'");
$response = array(
    'total' => $totalMsg,
    'extra' => 'extra value (if needed)'
);

5- echo在json编码:

echo json_encode($response);

之后,你可以像这样用jQuery访问你的值:

$.ajax({
type: "POST",
url: '/BubbleStat.php',
cache: false,
dataType: 'json',
success: function(jsonData)
    {
        if (jsonData.total != null && jsonData.total != undefined)
        {                
            $("#Bubble_Msg").text(jsonData.total).show();
        } 
    } 
});