2016-07-23 58 views
1

我學習角2和我做一個測試連接到數據庫,但我得到一個錯誤:語法錯誤:在JSON意外的標記<在位置0角2服務不調用PHP文件

所以我有我的xampp端口80或443上工作。 我的測試(我使用角度cli)的網址是:localhost:4200

這是我的嘗試。我有這種方法的服務:

getUsers(){ 
return this._http.get('getusers.php') 
    .map(res => res.json()); 
} 

getusers.php文件位於公用文件夾。 這是它的內容。非常基本的只是得到一些結果,然後傳回的JSON:

// set up the connection variables 
    $db_name = 'mydb'; 
    $hostname = 'localhost'; 
    $username = 'myusername'; 
    $password = 'mypass'; 

    // connect to the database 
    $dbh = new PDO("mysql:host=$hostname;dbname=$db_name", $username, $password); 


    $sql = 'SELECT * FROM users'; 


    $stmt = $dbh->prepare($sql); 


    $stmt->execute(); 


    $result = $stmt->fetchAll(PDO::FETCH_ASSOC); 


    $json = json_encode($result); 

    echo $json; 

,所以我補充一點,我導入服務組件,初始化它的構造函數和訂閱:

constructor(private _usersService: UsersService) {} 

    ngOnInit() { 
    this._usersService.getUsers() 
     .subscribe(
     data => this.getUsers = JSON.stringify(data), 
     error => alert(error), 
     () => console.log("Finihed") 
    ); 
    } 

什麼時我在這裏失蹤。我做了大量的ajax調用,但第一次有角度。也許是港口?或者我失蹤的其他東西?

最好的問候

+0

That _「SyntaxError:JSON中的意外標記」_可能意味着您的php有錯誤。確保你有一個完全可以工作的PHP代碼。 (你可以使用chrome的POSTMAN擴展來處理一些奇怪的請求) – FirstOne

+0

由於你沒有發送任何東西,所以從瀏覽器訪問'getusers.php'。你看到了什麼? – FirstOne

+0

我知道。我做的第一件事是檢查文件initself,我做了一個var_dump並獲取數據 – Ron

回答

1

如此以來,情況與兩個端口的跨域。在你的電話使用完整的URL與端口: http://localhost:80/yourproject/public/getContacts.php

並在服務器端添加CORS標頭之前輸出:

header("Access-Control-Allow-Origin: *"); 
header('Access-Control-Allow-Headers: X-Requested-With'); 
header('Content-Type: application/json'); 

echo json_encode($result); 

,因爲我只是在測試中,我使用*,但這不是推薦的。通常允許一個特定的網址。

0

您需要訂閱ajax調用才能工作; 誰曾經被調用getUsers方法應該訂閱它:

getUsers(){ 
    return this._http.get('getusers.php') 
    .map(res => res.json()); 
} 

比方說,你在這裏調用get方法:

myOtherFunction(){ 
    this.getUsers.subscribe((response)=>{ 
      console.log('response',response); 

    }) 

} 
+0

嘿,對不起,我忘了添加這個。在我的組分i導入該服務,然後該: 'ngOnInit(){ this._usersService.getUsers() .subscribe( 數據=> this.getUsers = JSON.stringify(數據),誤差 =>警報(錯誤), ()=> console.log(「Finihed」) ); }' – Ron