大家好,我在获取PHP脚本返回的对象json时遇到了问题。
当服务器返回对象 json 并且我以角度恢复对象时,我收到此错误。如果我从代码中删除 json 转换 res.json(( 此错误,则服务器响应为空。
ERROR SyntaxError: Unexpected token in JSON at position 0
at Object.parse (<anonymous>)
at Response.webpackJsonp.../../../http/@angular/http.es5.js.Body.json (http.es5.js:797)
at SafeSubscriber._next (list-alunos.component.ts:14)
at SafeSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.SafeSubscriber.__tryOrUnsub (Subscriber.js:238)
at SafeSubscriber.webpackJsonp.../../../../rxjs/Subscriber.js.SafeSubscriber.next (Subscriber.js:185)
at Subscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber._next (Subscriber.js:125)
at Subscriber.webpackJsonp.../../../../rxjs/Subscriber.js.Subscriber.next (Subscriber.js:89)
at XMLHttpRequest.onLoad (http.es5.js:1226)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:424)
at Object.onInvokeTask (core.es5.js:3881)
我有一个恢复信息的服务和使用此服务的组件:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/Rx';
@Injectable()
export class ApiHttpDaoService {
constructor(private http: Http) { }
public getListStudents() {
return this.http.get("http://localhost/obtener_alunos.php");
}
}
这是组件:
import { Component, OnInit } from '@angular/core';
import { ApiHttpDaoService } from '../../services/api-http-dao.service';
@Component({
selector: 'app-list-alunos',
templateUrl: './list-alunos.component.html',
styleUrls: ['./list-alunos.component.css']
})
export class ListAlunosComponent implements OnInit {
constructor(private service: ApiHttpDaoService) {
this.service.getListStudents().subscribe(
res => console.log(res.json())
);
}
ngOnInit() { }
}
这是返回 json 对象的 PHP 文件:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
require("conectar_mysql.php");
$vec_res = array();
$result = mysqli_query($conn, "SELECT * FROM alunos");
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
array_push($vec_res, array('nome' => $row['nome'], 'idade' =>
$row['idade'], 'morada' => $row['morada']));
}
echo json_encode($vec_res);
}
mysqli_close($conn);
?>
谢谢
您正在设置Content-type
标头两次。摆脱第二个,header('Content-Type: text/html; charset=utf-8');
你需要映射你的请求:
public getListStudents() {
return this.http.get("http://localhost/obtener_alunos.php")
.map(res => {return res;})
}