通过JSON传递变量


pass variable via JSON

脚本:

 $.ajax({
    method: "POST",
    //dataType: "json", //type of data
    crossDomain: true, //localhost purposes
    url: "./query/cate_has_courses.php", //Relative or absolute path to file.php file
    data: {id: i},
    success: function(response) {
        console.log(JSON.parse(response));
        var course=JSON.parse(response.query);
        var row=JSON.parse(response.rows);
        var el="";
        for(var j=0;j<NUMBER_OF_ELEMENTS;j++){
         $(document).on("click", ".category#i"+[j+1], loadSingleCourse);
            el+="<br><br><p style='font-size:18px'>"+course[j].title+"</p></div>";   
        }
                    $(".contenitore-dinamico").append(el);
    },
    error: function(request,error)
    {
        console.log("Error");
    }
});

PHP:

<?php
//get all the course from db and reply using json structure
//connection to db
$mysqli = new mysqli("localhost", "root", "", "my_hyp");
$id = $_POST['id'];
if (mysqli_connect_errno()) { //verify connection
    exit(); //do nothing else 
}
else {

    # extract results mysqli_result::fetch_array
    $query = " SELECT * FROM course WHERE course_category='$id'";
    //query execution
    $result = $mysqli->query($query);
    //if there are data available
    if($result->num_rows >0)
    {
        $myArray = array();//create an array
        while($row = $result->fetch_array(MYSQL_ASSOC)) {
            $myArray[] = array_map('utf8_encode', $row);
        }
        echo json_encode($myArray);
    }
    //free result
    $result->close();
    //close connection
    $mysqli->close();
}
?>

我不知道我必须在script.js中的"NUMBER_OF_ELEMENTS"变量中放入什么,因为我有一个外键的查询请求,而且我不知道结果的数量是多少。也许我必须输入行数?如何通过json传递它?谢谢你的帮助!

假设JSON已被正确解析:

    for(var j=0;j<row.length;j++){
        $(document).on("click", ".category#i"+[j+1], loadSingleCourse);
            el+="<br><br><p style='font-size:18px'>"+course[j].title+"</p></div>";   
    }

我尝试了(JSON.parse(response).length),它能在中工作