【问题标题】:Ionic and PHP 'Unexpected token < in JSON' errorIonic 和 PHP 'Unexpected token < in JSON' 错误
【发布时间】:2018-12-10 16:09:06
【问题描述】:

我是 ionic 新手,想知道我的脚本是错误还是 ionic 代码错误。它抛出这个错误:

ERROR SyntaxError: Unexpected token

我仔细检查了一切,但没有成功!我怀疑它是 PHP 文件,这就是我想要被引导的原因!

home.ts

import { Component, ViewChild } from '@angular/core';
    import { NavController, AlertController } from 'ionic-angular';
    import { RegisterPage } from '../register/register';
    import {Http, Headers, RequestOptions}  from "@angular/http";        
    import { LoadingController } from 'ionic-angular';        
    import 'rxjs/add/operator/map';

    @Component({
      selector: 'page-home',
      templateUrl: 'home.html'
    })
    export class HomePage {
      @ViewChild("username") username;        
      @ViewChild("password") password;          
      data:string;

    constructor(public navCtrl: NavController, public alertCtrl: AlertController,        
    private http: Http, public loading: LoadingController)  {}

      signUp(){        
          this.navCtrl.push(RegisterPage);          
        }

        signIn(){        
          //// check to confirm the username and password fields are filled

          if(this.username.value=="" ){              
          let alert = this.alertCtrl.create({              
          title:"ATTENTION",              
          subTitle:"Username field is empty",              
          buttons: ['OK']              
          });

          alert.present();

          } else

          if(this.password.value==""){

          let alert = this.alertCtrl.create({

          title:"ATTENTION",

          subTitle:"Password field is empty",

          buttons: ['OK']

          });

          alert.present();

          }

          else

          {

          var headers = new Headers();

          headers.append("Accept", 'application/json');

          headers.append('Content-Type', 'application/json' );

          let options = new RequestOptions({ headers: headers });

          let data = {

          username: this.username.value,

          password: this.password.value

          };

          let loader = this.loading.create({

          content: 'Processing please wait…',

          });

          loader.present().then(() => {

          this.http.post('http://localhost/shashank/login.php',data,options)

          .map(res => res.json())

          .subscribe(res => {

          console.log(res)


          loader.dismiss()

          if(res=="Your Login success"){

          let alert = this.alertCtrl.create({

          title:"CONGRATS",

          subTitle:(res),

          buttons: ['OK']

          });
          alert.present();

          }else

          {

          let alert = this.alertCtrl.create({

          title:"ERROR",

          subTitle:"Your Login Username or Password is invalid",

          buttons: ['OK']

          });

          alert.present();

          }

          });

          });

          }

          }

          }

PHP 脚本login.php

<?php 
if (isset($_SERVER["HTTP_ORIGIN"])) {

        header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");

        header('Access-Control-Allow-Credentials: true');

        header('Access-Control-Max-Age: 86400');    // cache for 1 day


 }
    // Access-Control headers are received during OPTIONS requests

    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS')
     {

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))

            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");        

        if (isset($_SERVER["HTTP_ACCESS_CONTROL_REQUEST_HEADERS"]))

            header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    exit(0);  }   



  require "dbconnect.php";

    $data = file_get_contents("php://input");

    if (isset($data)) {

        $request = json_decode($data);

        $username = $request->username;

        $password = $request->password;

                }

      $username= mysqli_real_escape_string($con,$username);

      $password = mysqli_real_escape_string($con,$password);

       $username = stripslashes($username);

      $password = stripslashes($password);

    $sql = "SELECT id FROM users WHERE username = '$username' and password = '$password'";

      $result = mysqli_query($con,$sql);

      $row = mysqli_fetch_array($result,MYSQLI_ASSOC);

      $active = $row['active'];

      $count = mysqli_num_rows($result);



      // If result matched myusername and mypassword, table row must be 1 row                    

      if($count > 0) {

     $response= "Your Login success";

      }else {

    $response= "Your Login Email or Password is invalid";       

      }

 echo json_encode( $response);

?>

控制台输出:

  core.js:1449 ERROR SyntaxError: Unexpected token < in JSON at position 0
            at JSON.parse (<anonymous>)
            at Response.Body.json (http.js:1091)
            at MapSubscriber.project (home.ts:97)
            at MapSubscriber._next (map.js:79)
            at MapSubscriber.Subscriber.next (Subscriber.js:93)
            at XMLHttpRequest.onLoad (http.js:1591)
            at t.invokeTask (polyfills.js:3)
            at Object.onInvokeTask (core.js:4751)
            at t.invokeTask (polyfills.js:3)
            at r.runTask (polyfills.js:3)

【问题讨论】:

  • 生成的 JSON 字符串包含什么?
  • 字符串值我不知道得到
  • 提供包含在 $data 变量中的 json 数据。
  • 生成的 JSON 字符串究竟包含什么?为什么你认为对字符串进行编码会创建一个有效的 JSON 对象?

标签: javascript php ionic-framework


【解决方案1】:

这意味着您正在尝试解析无效 json 格式的数据(例如,它的开头是 &lt; 而不是 {)。

在你的home.ts:

...
this.http.post('http://localhost/shashank/login.php',data,options)
      .map(res => res.json())
      .subscribe(res => {
      console.log(res)
...

这个请求很可能没有返回一个有效的 json,当它试图用res.json() 解析它时,它返回了这个错误。

现在,在您的login.php 中,您需要检查它是否返回valid json

【讨论】:

    猜你喜欢
    • 2017-01-17
    • 2022-01-22
    • 2021-01-10
    • 1970-01-01
    • 2019-05-23
    • 1970-01-01
    • 2021-05-29
    • 2016-11-03
    • 2019-11-17
    相关资源
    最近更新 更多