2017-06-17 135 views
-2

我正在使用AJAX調用來請求服務器上的PHP文件。 PHP文件包含一些對象。正在使用JSON.parse()將結果轉換爲JavaScript對象。所以,問題是運行程序我看到下面的錯誤在瀏覽器控制檯後:從服務器上的PHP文件獲取數據作爲JSON

Uncaught SyntaxError: Unexpected end of JSON input 
at JSON.parse (<anonymous>) 
at XMLHttpRequest.xmlhttp.onreadystatechange (index.php:15) 

我不知道爲什麼程序不能正常工作,雖然我的Apache服務器,和PHP運行良好。 我的工作程序:

的index.php:

<p id="demo"></p> 

<script> 

var xmlhttp = new XMLHttpRequest(); 

xmlhttp.onreadystatechange = function() { 
    if (this.readyState == 4 && this.status == 200) { 
     myObj = JSON.parse(this.responseText); 
     document.getElementById("demo").innerHTML = myObj.name; 
    } 
}; 
xmlhttp.open("GET", "demo_file.php", true); 
xmlhttp.send(); 

</script> 

demo_file.php:

<?php 
$myObj->name = "John"; 
$myObj->age = 30; 
$myObj->city = "New York"; 

回答

1

也許你有一個警告:$ myObj沒有初始化:

<?php 
header('Content-type: text/json'); 
$myObj = new stdClass; 
$myObj->name = "John"; 
$myObj->age = 30; 
$myObj->city = "New York"; 
echo json_encode($myObj); 
+0

非常感謝。我想要抱你! –

4

您可以構建在PHP JSON與json_encode()功能:

<?php 

$myObj = new stdClass(); 
$myObj->name = "John"; 
$myObj->age = 30; 
$myObj->city = "New York"; 

echo json_encode($myObj); 
+0

穆罕默德Hamedani,thnaks爲您的答案。我已經知道了。但我想讓XMLHTTP請求從文件中獲取數據。在這種情況下,PHP文件位於服務器中,Javascript是一個客戶端程序 - 這正是我在我的程序中試圖做的,而且它不工作。你能幫助我嗎? –

+0

你有沒有想過這個問題? –