通过JSON

时间:2015-06-02 08:59:41

标签: javascript php ajax 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传递它?谢谢你的帮助!

2 个答案:

答案 0 :(得分:0)

假设已正确解析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>";   
    }

答案 1 :(得分:0)

我尝试了(JSON.parse(response).length)并且有效

相关问题