缺少jquery ajax成功设置



我有一个简单的复选框,可以通过查询数据库来打开或关闭它。用户可以更改此值,我通过ajax发送请求。这个url很古怪,因为它是Joomla组件(对于这个问题不重要,只是以防万一)。

$(function() {
$("#iButton").iButton();
$('#iButton').change(function() {
var checkedLength = $(this + ':checked').length;
if(1 == checkedLength){
$.ajax({
url: 'index.php?option=com_mycomponent&task=globaldetection&id_hash=<?php echo $id_hash; ?>&global_monitoring='+checkedLength+'&format=raw'
});
} else {
$.ajax({
url: 'index.php?option=com_mycomponent&task=globaldetection&id_hash=<?php echo $id_hash; ?>&global_monitoring='+checkedLength+'&format=raw'
});
}
});
});
<?php
//highlight whether the checkbox is on or off
if ($userstatus == "ENABLED") //get this value from server
{
//turned on
$global_monitoring = "checked="checked"";
}
else
{
$global_monitoring = "";
}
?>
<div class="dropshadow">
<p id="iButtontext">
<input type="checkbox" id="iButton" <?php echo $global_monitoring; ?> name="iButton_checkbox" />
</p>
</div>

这很好,正如我所期望的,但我有几个问题:

  1. 我根据条件重复ajax函数两次。有没有更好的方法可以做到这一点或完全可以接受
  2. 我只传入url,没有其他设置。我一直使用success设置,但在这种情况下,我不需要做其他响应。我知道这是可选的,但此时我应该做其他事情吗
  3. 我应该将其他设置传递到ajax中吗?只是看起来太。。。简单

欢迎提供任何指导。谢谢

您根本不需要if/else结构,因为在两个分支中,您都有一行相同的代码,所以如果您只将这行代码单独放置,它就会工作(它仍然使用checkedLength的值)。

但是,$(this + ':checked').length没有意义——您的选择器将字符串':checked'连接到对象this的末尾。我现在不明白这是怎么回事。将结果作为"长度"的等效方法是$(this).filter(':checked').length,这有点笨拙。或者,您可以用if ($(this).is(':checked'))将其测试为布尔值,但即使这样也比this.checked执行相同任务时需要的复杂得多。

假设您可以直接使用this.checked获得检查状态,我认为以下操作更简单(而且肯定更有效):

$('#iButton').change(function() {
$.ajax({
url: 'index.php?option=com_mycomponent&task=globaldetection&id_hash=<?php echo $id_hash; ?>&global_monitoring='
+ (this.checked ? 1 : 0) + '&format=raw'
});
});

(我假设您最初使用的.length只能是01,因为事件位于您通过id选择的元素上。)

"我只传递url,没有其他设置。我一直使用成功设置,但在这种情况下,我不需要做其他响应。我知道这是可选的,但我应该在那一点上做其他事情吗?">

否。如果你不需要对成功做任何事情,那么就不要指定成功回调——不过,如果由于某种原因调用不起作用,那么指定错误回调可能是明智的。

最新更新