通过ajax从php响应中输入html属性

时间:2016-07-04 08:49:17

标签: php jquery json ajax

我试图调用ajax(它的工作原理)来检索一个带有复选框prev检查的数组,但不起作用,我认为问题可以在jQuery.inArray中找到,为什么其余的工作

<input type="checkbox" class="controla" name="control[]"  value="0">
<input type="checkbox" class="controla" name="control[]"  value="1">
<input type="checkbox" class="controla" name="control[]"  value="2">
....

Jquery就像这样展示

(function( $ ){
   $.fn.cargaTabla = function() {
        $.ajax({
             type: "POST",
                    url: "AccionesPrueba.php?accion=controles",
                    data: {fecha : '25'},
                    success: function(response) {
                        var controles = jQuery.parseJSON(response);
                        $('.controla').each(function(){
                            if (jQuery.inArray(jQuery(this).val(), controles) != -1){
                                this.attr('checked', 'checked');
                            }
                        });
                    }
            });
        };
    })( jQuery );

        $().cargaTabla();

AccionesPrueba.php

if($_GET["accion"] == "controles"){

    $fecha = $_POST['fecha'];

    $sql = "SELECT Control FROM registros WHERE Fecha = $fecha";
    $resultado = $db->consulta($sql); //call class for DB access
    if (mysqli_num_rows($resultado) > 0) {
        while($row = mysqli_fetch_assoc($resultado)) {
            $datos = $row['Control'];
            $extraeDatos = explode(",", $datos);
            echo json_encode ($extraeDatos);
       }
    }
}
来自registros表的

行控制显示例如1,2,7

3 个答案:

答案 0 :(得分:0)

你将你的类型设置为POST。所以必须通过$ _POST调用,并且应该将你的para更改为data: {accion:'controles',fecha : '25'}。我认为你的返回json数据是int所以你应该将你的复选框值更改为首先int,然后比较它。

 $('.controla').each(function(){
         var check_value = parseInt(jQuery(this).val());
         if (jQuery.inArray(check_value , controles) != -1){
                jQuery(this).attr('checked', 'checked');
           }
  });

不要忘记将jQuery添加到您的this代码中。

答案 1 :(得分:0)

我发现了问题

this.attr('checked', 'checked');

$(this).attr('checked', 'checked');

谢谢!

答案 2 :(得分:-1)

只需使用.each函数预定义params .each(index,element)。

                        $('.controla').each(function(idx, elmt){
                            if (jQuery.inArray(jQuery(elmt).val(), controles) != -1){
                                $(elmt).prop('checked', true);
                            }
                        });