首页 > 解决方案 > 如何使用 php 和 ajax 从同一个切换开关触发两个不同的事件

问题描述

关闭图像 上的图像开关 我想制作一个切换开关,它需要使用 php 和 ajax 从同一个切换开关触发两个不同的事件,我在下面的 html 代码中做了这个

<div id="about-btn" class="card-action">
   <div class="about-btn">
     <input type="checkbox" id="cfl" name="cfl" class="switch-input">
	    <label for="cfl" class="switch-label"><h4>CFL&nbsp;<span class="toggle--on">ON</span><span class="toggle--off">OFF</span></h4></label>
   </div>
</div>

& 跟随 php 代码

<?php

if(isset($_POST['cfl'])) {
   makeRequest('cfl_on'); // user checked the box
} else {
   makeRequest('cfl_off'); // user did not check the box
}

?>  

这个 php 需要将值传递给我的脚本的“makeRequest()”函数

<script>
function makeRequest(actionParam){
    var request = $.ajax({
      url: "controller.php",
      type: "POST",
      data: {Action : actionParam},
      dataType: "html"
    });

    request.done(function(msg) {
        //alert(msg);
      // $("#ResponseDiv").html( msg );
    });

    request.fail(function(jqXHR, textStatus) {
      alert( "Request failed: " + textStatus );
    });
}

我知道我做错了什么,但无法弄清楚。任何帮助将不胜感激。在此先感谢您的帮助。

标签: javascriptphpjqueryhtmlajax

解决方案


如果你想做两个不同的 ajax 调用:

$('.switch-label').on('click', function(){
    if($('#cfl').is(':checked'){
        "make ajax call 1 here"
    }
    else{
        "make ajax call 2 here"
    }
});

或者,如果您只想隐藏/显示您的图像,而不仅仅是在单击 $('cfl') 时切换图像容器


推荐阅读