我正在使用Ionic 2框架处理项目,但我收到了意外令牌错误<在JSON的第0位home.ts:37,每当我向MySQL数据库提交表单输入时。我检查了我的端口,一切正常。可能导致这个问题的原因是什么?
完整错误
SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at Response.Body.json (http.es5.js:800)
at MapSubscriber.project (service.ts:28)
at MapSubscriber._next (map.js:77)
at MapSubscriber.Subscriber.next (Subscriber.js:89)
at XMLHttpRequest.onLoad (http.es5.js:1229)
at t.invokeTask (polyfills.js:3)
at Object.onInvokeTask (core.es5.js:4119)
at t.invokeTask (polyfills.js:3)
at r.runTask (polyfills.js:3)
launch.json
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"program": "${file}",
"outFiles": [
"${workspaceRoot}/out/**/*.js"
]
}
]
}
这是我的代码:
home.html的
<ion-header>
<ion-navbar>
<ion-title>
Agregar producto
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<form [formGroup]="insertar" (ngSubmit)="InsertarProducto()">
<ion-list>
<ion-item>
<ion-label floating>nombre</ion-label>
<ion-input type="text" name="nombre" formControlName="nombre" ></ion-input>
</ion-item>
<ion-item>
<ion-label floating>stock</ion-label>
<ion-input type="text" name="stock" formControlName="stock" ></ion-input>
</ion-item>
<button [disabled]="insertar.invalid" ion-button full block color="secondary">Enviar</button>
</ion-list>
</form>
</ion-content>
home.ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { ServiceProvider } from '../../providers/service/service';
import { FormBuilder, Validators } from '@angular/forms';
import { ToastController } from 'ionic-angular';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
insertar : any = {};
constructor(public navCtrl: NavController , public service : ServiceProvider, public formB : FormBuilder, public toastCtrl: ToastController)
{
this.insertar = this.formB.group({
nombre:['', Validators.required],
stock:['', Validators.required]
});
}
InsertarProducto(){
/*let toast = this.toastCtrl.create({
message: 'Usuario agregado correctamente',
duration: 3000
});*/
this.service.InsertarProd(this.insertar.value)
.subscribe(
data=> console.log(data.mensage), //toast.present()
err=> console.log(err));
}
}
service.ts
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/map';
import { Http , Headers, Response} from '@angular/http';
//import { Observable } from "rxjs/Observable";
/*
Generated class for the ServiceProvider provider.
See https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more info on providers and Angular 2 DI.
*/
@Injectable()
export class ServiceProvider {
api : string = 'http://localhost:8080/ING/';
constructor(public http: Http) {
console.log('Hello ServiceProvider Provider');
}
InsertarProd(params){
let headers = new Headers({'Content-Type':'application/x-www-form-urlencoded'});
return this.http.post(this.api + 'insertarprod.php' , params,{
headers:headers,
method:"POST",
}).map(
(res:Response)=>{return res.json();}
)
}
}
insertarprod.php
<?php
header("Access-Control-Allow-Origin:http://localhost:8100");
header("Content-Type: application/x-www-form-urlencoded");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");
$data = file_get_contents("php://input");
$objData = json_decode($data);
$nombre = $objData->nombre;
$stock = $objData->stock;
$nombre = stripslashes($nombre);
$stock = stripslashes($stock);
$nombre = trim($nombre);
$stock = trim($stock);
$datos;
@$db = new PDO("mysql:host=localhost;dbname=aula", "root", "");
$prueba = array('mensaje2' => "conexion correcta");
echo json_encode($prueba);
if($db){
$sql = " insert into productos values(NULL,'".$nombre."','".$stock."')";
$query = $db->prepare($sql);
$query ->execute();
if(!$query){
$datos = array('mensage' => "no fue posible insertar datos");
echo json_encode($datos);
}
else{
$datos = array('mensage' => "Datos ingresados correctamente");
echo json_encode($datos);
};
}
else{
$datos = array('mensage' => "No es posible insertar datos.");
echo json_encode($datos);
};
?>
答案 0 :(得分:0)
将您的JSON复制/粘贴到验证器中,如下所示:https://jsonformatter.curiousconcept.com/
如果您仍然无法找到它,请在问题中与我们分享JSON。
答案 1 :(得分:0)
除了评论之外,你的json是有效的: https://jsonlint.com/ 请参阅:Can comments be used in JSON?关于json文件中的注释。
答案 2 :(得分:0)
由于某种原因,我在3307的XAMPP SQL端口导致错误。我将其更改回3306,我的代码使用0 JSON错误。