Javascript 使用本地AJAX请求解析JSON数据
我在Web服务器上有一个php文件,它执行对MySQL数据库的查询 我正在我的pc(本地)上测试一个站点,该站点使用带有AJAX请求的js文件从该php文件获取JSON数据 可以这样做吗,或者js文件必须放在php文件的同一个域服务器上 因为解析数据的Javascript 使用本地AJAX请求解析JSON数据,javascript,php,mysql,ajax,json,Javascript,Php,Mysql,Ajax,Json,我在Web服务器上有一个php文件,它执行对MySQL数据库的查询 我正在我的pc(本地)上测试一个站点,该站点使用带有AJAX请求的js文件从该php文件获取JSON数据 可以这样做吗,或者js文件必须放在php文件的同一个域服务器上 因为解析数据的console.log给了我以下错误: 未捕获的语法错误:意外的标记I 这是ajax调用 $.ajax({ method:"POST", crossDomain:true, url:"url for the php fi
console.log
给了我以下错误:
未捕获的语法错误:意外的标记I
这是ajax调用
$.ajax({
method:"POST",
crossDomain:true,
url:"url for the php file",
data:{
query: "SELECT * FROM course_categories;"
},
success: function(response){
var course_categories=JSON.parse(response);
console.log(course_categories);
var el="";
console.log(course_categories.length);
for(var i=0;i<(course_categories.length);i++)
{
}
},
error: function(request,error){
console.log("ERROR: Request " + request + "\nSpecific Error: " + error);
}
$.ajax({
方法:“张贴”,
跨域:是的,
url:“php文件的url”,
数据:{
查询:“从课程类别中选择*
},
成功:功能(响应){
var course_categories=JSON.parse(响应);
控制台日志(课程类别);
var el=“”;
控制台。日志(课程类别。长度);
对于(var i=0;i我做到了。我所要做的就是删除crossDomain:true
行,这样JSON就可以真正解析数据了。你能提供你的代码吗?你能分享一些吗code@RiccardoLomazzi——这是因为您的PHP代码中有一些错误,javascript无法将其读取或解析为JSONde,您将解决该问题:)我添加了一些代码控制台中的确切响应是什么?函数utf8ize
做什么?
<?php
//get all the courses from the database and reply using the JSON structure
//$mysqli=new msqli("localhost","username","password","dbname");
$mysqli=new mysqli("localhost","hey","","db_name");
if(mysqli_connect_errno()) //returns a number of the error if there is any, if not
{
echo json_encode("Error to connect to DBMS".mysqli_connect_error());
exit(); //closes the connection
}
else
{
$query=$_POST["query"];
//$query="SELECT * FROM course_categories";
$result=$mysqli->query($query); //do a query (->query) setted by $query, using the $mysqli variable, and store the data in $result
if($result->num_rows >0) //if there is at least one row...
{
$myArray= array(); //...create an array...
while($row = $result->fetch_array(MYSQL_ASSOC))
{
//...and fetch it. Everytime this operation returns a row,
$myArray[]=$row; //...and added to myArray ([] means autoincrement).
}
}
echo json_encode(utf8ize($myArray));
//free result
$result->close();
//close connection
$mysqli->close();
}