循环Json中的错误来自ajax中的查询

时间:2018-01-15 00:31:39

标签: javascript php jquery json ajax

我正在尝试使用ajax检索BD的信息。 问题是,当我从脚本php收到数据时,它向我发送了一个json文件,但是我无法打印这些值,这是我的代码。

JS:

$(document).ready(()=>{

    $('table').on("click", "p",  function(){
        let value = $(this).attr('value')
        if (value=='true') {
            $(this).addClass('disabled')
            let data = $(this).attr('data-value')
            var info = {
                "numSelection":data,
                "sort": "97"
            }
            $.ajax({
                data:info,
                url:"js/service.php",
                type:"post",
                beforeSend:function(){
                    console.log("Estamos en proceso con ajax")// Here we are fine
                }
            }).done(function(data){
                console.log(data)//this print the json file in console 
                                correctly
                $.each(data,function(i,item){//here is the error in console
                    console.log("Index: "+i)
                    console.log("Item: "+item)
                })              

            })          
        }
    });
});

在此步骤中,我在控制台上收到此错误:

  

未捕获TypeError:无法使用'in'运算符在+ json文件的内容中搜索'957'

这是我的带有sql的php脚本

<?php 
// var_dump();
// error_reporting(E_ERROR | E_WARNING | E_PARSE);
include('conn.php');
$sql = "SELECT * FROM participantes WHERE sorteos_id=".$_POST['sorteo'].";";
$result = mysqli_query($conn, $sql);
$resultado = mysqli_fetch_array($result);
$enviar = array();
if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        $enviar[]=$row;
    }
} else {
    echo "0 results";
}

echo json_encode($enviar);
?>

如果我不以json格式发送信息,则会以数组形式发送,但会显示恼人的消息

  

注意 C:\ UwAmp \ www \ testing \ js \ service.php 中的数组到字符串转换 19
      阵列

我是新编码所以我接受任何建议

1 个答案:

答案 0 :(得分:0)

非常感谢你们帮我解决这个问题。但他们给了我很多想法,所以我找到了答案......

我的错误是,不要指定我在等什么格式,只需添加  dataType: "json的配置中的$.ajax

$.ajax({
  data: info,
  url: "js/service.php",
  type: "post",
  dataType: "json", //this to receive json
  beforeSend: function() {
    console.log("Estamos en proceso con ajax")
  }
}).done(function(data) {
  console.log(data)
  $.each(data, function(i, item) {
    console.log("Index: " + i)
    console.log("Item: " + item)
  })

})

<强> PHP

$result = mysqli_query($conn, $sql);
    $resultado = mysqli_fetch_array($result);
    $enviar = array();
    if (mysqli_num_rows($result) > 0) {
        // output data of each row
        while($row = mysqli_fetch_assoc($result)) {
            $enviar[]=$row;
        }
    } else {
        echo "0 results";
    }
    echo json_encode($enviar);//this to send json