2015-05-31 27 views
0

我在執行查詢到MySQL數據庫的web服務器上有一個php文件。用本地AJAX請求解析JSON數據

我在我的電腦(本地)上測試一個站點,該站點使用帶有AJAX請求的js文件從該php文件獲取JSON數據。

是否有可能這樣做,或者js文件必須放在php文件的同一域服務器上?

因爲分析數據的console.log給了我這個錯誤:

Uncaught SyntaxError: Unexpected token 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); 
    } 

雖然這是PHP調用

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

} 
+0

你能否提供你的代碼? –

+0

可以請分享一些代碼 – JazzCat

+0

@Riccardo Lomazzi - 這是因爲你的PHP代碼有一些錯誤,JavaScript無法讀取或解析爲JSON。檢查你的PHP代碼,你會解決這個問題:) – DDeme

回答

0

我做它。我所要做的就是刪除crossDomain:true行,以便JSON實際上可以解析數據。