duai0935 2015-05-31 13:39
浏览 86
已采纳

使用本地AJAX请求解析JSON数据

I've got a php file on a webserver that executes queries to a MySQL database.

I'm testing a site on my pc (locally) that uses a js file with an AJAX request to get JSON data from that php file.

Is it possible to do it like this, or the js file must be put on the same domain server of the php file?

Because the console.log of the parsed data gives me this error:

Uncaught SyntaxError: Unexpected token I

This is the ajax call

$.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 + "
Specific Error: " + error);
    }

While this is the PHP call

<?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(); 

}
  • 写回答

1条回答 默认 最新

  • douxun4924 2015-05-31 16:46
    关注

    I did it. All I had to do, was to remove the crossDomain:true line so that the JSON could actually parse the data.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题
  • ¥60 高价有偿求java辅导。工程量较大,价格你定,联系确定辅导后将采纳你的答案。希望能给出完整详细代码,并能解释回答我关于代码的疑问疑问,代码要求如下,联系我会发文档
  • ¥50 C++五子棋AI程序编写
  • ¥30 求安卓设备利用一个typeC接口,同时实现向pc一边投屏一边上传数据的解决方案。
  • ¥15 SQL Server analysis services 服务安装失败
  • ¥15 基于面向对象的图书馆借阅管理系统
  • ¥15 opencv图像处理,需要四个处理结果图
  • ¥20 centos linux 7.9安装php8.2.18不支持mysqli模块的问题
  • ¥15 stata空间计量LM检验
  • ¥15 关于k8s node节点被释放后如何驱逐节点并添加新节点