[英]pass variable via JSON
Script: 脚本:
$.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:
<?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();
}
?>
I don't know what i must put in "NUMBER_OF_ELEMENTS" variable in script.js, because i have a query request by foreign keys and i don't know a priori what is the number of the result. 我不知道我必须在script.js中的“ NUMBER_OF_ELEMENTS”变量中放什么,因为我有一个通过外键进行的查询请求,而且我也不知道先验结果的数量是多少。 Maybe i have to put the number of rows? 也许我必须输入行数? How can I pass it through json? 如何通过json传递? Thanks for help! 感谢帮助!
Assuming the JSON has been correctly parsed: 假设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)
,它有效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.