繁体   English   中英

通过JSON从php传递可变性到js

[英]Pass a variabile from php to js via JSON

在课程中,我学习了如何通过JSON / AJAX将来自sql请求的结果传递给js。 我需要在我的js中此请求的行的值,但它不起作用。 通过控制台,我遇到一个错误:未捕获的SyntaxError:意外的令牌<

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);
        }
        $response = array();        
        $response['rows'] = $row;
        $response['query'] =  $myArray;
        echo json_encode($response);
    }

    //free result
    $a=num_rows;
    $result,$a->close();

    //close connection
    $mysqli->close();
}



?>

脚本的第一部分:

 $.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);

似乎您以错误的方式使用JSON.parse。 JSON.parse必须仅完成一次。 JSON.parse的结果将存储在过程中,对数据的访问应通过response.query或respons.row ..依此类推,而不是通过JSON.parse(respose.query)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM