ajax成功的If /else语句
if/else statement on ajax success
我试图获得未读消息的计数器: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();
}
}
});
相关文章:
- 如何在ReactJS JSX中执行嵌套的if-else语句
- 如何检查if/else语句中的随机条件
- 在Javascript中为if/else语句添加OR
- geoTest函数-创建if/else语句
- Jquery/Javascript使用IF/ELSE语句更改img SRC
- 编写if-else语句的更好方法
- Javascript if和else语句不起作用
- 为什么它立即跳到我的else语句
- 空变量的 else 语句
- 在if/else语句中显示DIV
- 由 if / else 语句中的无效语法导致的语法错误
- jQuery 验证正在复制 else 语句 |验证完成后,不会打印值
- JavaScript if else 语句来显示 html 标签
- 如何做if/else语句并使用控制台.log打印出来
- 此 JavaScript 代码无法正常工作(if-else 语句)
- 不带花括号的If/else语句javascript
- 如何缩短if-else语句
- 用于筛选数据的函数--if.else语句
- 赢得't输入javascript if/else语句
- 打印出带有参数的if-else语句