我正在尝试从php文件获取JSON数据,但控制台显示以下错误:
EXCEPTION: Unexpected token < in JSON
我刚才通过PHP发送了一个简单的JSON数组,代码如下:
<?php
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Headers: X-Requested-With');
header('Content-Type: application/json');
$res = [
array(
'title' => 'First task',
'description' => 'skdfjsdfsdf',
'done' => false,
),
array(
'title' => 'Second task',
'description' => 'skdfjsdfsdf',
'done' => false,
),
array(
'title' => 'Third task',
'description' => 'skdfjsdfsdf',
'done' => false,
)
];
echo json_encode(array('tasks' => $res));
这是我的php文件位置:
![enter image description here](https://istack.dev59.com/bB9Vm.webp)
最后,这是我的服务类:
import { Injectable } from '@angular/core';
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class TasksDataService {
constructor(private http: Http) {}
getTasks(){
return this.http.get('http://localhost:4200/src/database.php')
.map(res => {
console.log(res.json());//--I get the error in this line
var result = res.json().tasks;
console.log(result);
return result;
});
}
}
我为这个问题搜索了很多,尝试了很多解决方案,但仍然得到相同的错误!