简体   繁体   English

SyntaxError: JSON JSON JSON.parse 0 中的意外标记

[英]SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse

I created an application with ionic with the help of this tutorial: http://masteringionic.com/blog/2016-12-15-using-php-and-mysql-with-ionic/ a school programm我在本教程的帮助下使用 ionic 创建了一个应用程序: http://masteringionic.com/blog/2016-12-15-using-php-and-mysql-with-ionic/一个学校程序

But when i want to select all my client, i get this error:但是当我想要 select 我所有的客户时,我得到这个错误:

SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at XMLHttp…, text SyntaxError: 意外令牌 < in JSON at position 0 at JSON.parse () at XMLHttp..., text

My PHP script:我的 PHP 脚本:

    <?php

   // Define database connection parameters
   $hn      = 'localhost';
   $un      = 'root';
   $pwd     = '';
   $db      = 'equida';
   $cs      = 'utf8';


   // Set up the PDO parameters
   $dsn     = "mysql:host=" . $hn . ";port=3306;dbname=" . $db . ";charset=" . $cs;
   $opt     = array(
                        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
                        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ,
                        PDO::ATTR_EMULATE_PREPARES   => false,
                       );
   // Create a PDO instance (connect to the database)
   $pdo     = new PDO($dsn, $un, $pwd, $opt);
   $data    = array();


   // Attempt to query database table and retrieve data
   try {
      $stmt     = $pdo->query('SELECT * FROM client');
      while($row  = $stmt->fetch(PDO::FETCH_OBJ))
      {
         // Assign each row of data to associative array
         $data[] = $row;
      }

      // Return data as JSON
      echo json_encode($data);
   }
   catch(PDOException $e)
   {
      echo $e->getMessage();
   }


?>

My javascript:我的 javascript:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'page-lst-client',
  templateUrl: 'lst-client.html'
})
export class LstClientPage {
   /**
    * @name items
    * @type {Array}
    * @public
    * @description     Used to store returned PHP data
    */
   public items : Array<any> = [];

   constructor(public navCtrl: NavController,
               public http   : HttpClient)
   {

   }


   /*
    * Triggered when template view is about to be entered
    * Returns and parses the PHP data through the load() method
    *
    * @public
    * @method ionViewWillEnter
    * @return {None}
    */
   ionViewWillEnter() : void
   {
      this.load();
   }


   /*
    * Retrieve the JSON encoded data from the remote server
    * Using Angular's Http class and an Observable - then
    * assign this to the items array for rendering to the HTML template
    *
    * @public
    * @method load
    * @return {None}
    */
   load() : void
   {
      this.http
      .get('wequida/retrieve-client.php')
      .subscribe((data : any) =>
      {
         console.dir(data);
         this.items = data;
      },
      (error : any) =>
      {
         console.dir(error);
      });
   }


   /*
    * Allow navigation to the AddTechnologyPage for creating a new entry
    *
    * @public
    * @method addEntry
    * @return {None}
    */
   addEntry() : void
   {
      this.navCtrl.push('AddClientPage');
   }


   /*
    * Allow navigation to the AddTechnologyPage for amending an existing entry
    * (We supply the actual record to be amended, as this method's parameter,
    * to the AddTechnologyPage
    *
    * @public
    * @method viewEntry
    * @param param      {any}           Navigation data to send to the next page
    * @return {None}
    */
   viewEntry(param : any) : void
   {
      this.navCtrl.push('AddClientPage', param);
   }
}

Your getting an HTML response from your PHP script.您从 PHP 脚本获得 HTML 响应。

You should include a json header in your PHP script.您应该在 PHP 脚本中包含 json header。

header('Content-type: application/json');

The line线

echo $e->getMessage();

will not output JSON. Your javascript does not accommodate sending errors.不会 output JSON。您的 javascript 不包含发送错误。 In your PHP script you can use use:在您的 PHP 脚本中,您可以使用:

echo json_encode(array('error' => false, 'data' => $data));
...
echo json_encode(array('error' => $e->getMessage(), 'data' => []));

Then in your javascript:然后在您的 javascript 中:

.subscribe((result: any) =>
{
    if (result.error) 
    {
        // error handling code
    } 
    else
    {
        console.dir(result.data);
        this.items = result.data;
    }
},

If there is an error connecting to the database your script will output an HTML message with an 'Uncaught PDOException'.如果连接到数据库时出错,您的脚本将 output 和 HTML 消息,其中包含“Uncaught PDOException”。 You can wrap that in try/catch as well.您也可以将其包装在 try/catch 中。

To know what the problem is you should look at what your PHP script is outputting.要知道问题出在哪里,您应该查看 PHP 脚本输出的内容。
To do that要做到这一点

  • open the developers console [Option + ⌘ + J (on macOS), or Shift + CTRL + J (on Windows/Linux)],打开开发人员控制台 [Option + ⌘ + J(在 macOS 上)或 Shift + CTRL + J(在 Windows/Linux 上)],
  • go to the 'Network' tab, go 到“网络”选项卡,
  • reload the page,重新加载页面,
  • look for your php script and click on it,寻找您的 php 脚本并点击它,
  • open the 'Response' tab.打开“响应”选项卡。

You will see the raw HTML or JSON response from the PHP script.您将看到来自 PHP 脚本的原始 HTML 或 JSON 响应。

Edit - after reading comments:编辑 - 阅读评论后:

If in the Response tab you see the full unparsed content of the PHP file then the web server you are using is not parsing PHP. You might be trying to do this without a sever by opening an HTML file with the javascript above through the file system using file:///C:/something/whatever.html如果在 Response 选项卡中您看到 PHP 文件的完整未解析内容,那么您正在使用的 web 服务器未解析 PHP。您可能试图在没有服务器的情况下通过文件系统打开带有 javascript 的 HTML 文件来执行此操作使用 file:///C:/something/whatever.html
This will not work for obvious reasons.由于显而易见的原因,这将行不通。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未捕获到的SyntaxError:JSON中的意外令牌u在JSON.parse的位置0 - Uncaught SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse 未捕获的SyntaxError:JSON.parse中位置0的JSON中的意外标记a( <anonymous> ) - Uncaught SyntaxError: Unexpected token a in JSON at position 0 at JSON.parse (<anonymous>) JSON.parse() 导致错误:`SyntaxError: Unexpected token in JSON at position 0` - JSON.parse() causes error: `SyntaxError: Unexpected token in JSON at position 0` JSON.parse(): SyntaxError: Unexpected token in JSON at position 0 - JSON.parse(): SyntaxError: Unexpected token � in JSON at position 0 JSON.parse() 错误 SyntaxError: Unexpected token &lt; in JSON at position 0 - JSON.parse() Error SyntaxError: Unexpected token < in JSON at position 0 语法错误:JSON 中的意外令牌 e 在 position 1 与 JSON.parse() - SyntaxError: Unexpected token e in JSON at position 1 with JSON.parse() SyntaxError:JSON中的意外令牌u在JSON.parse( <anonymous> ) - SyntaxError: Unexpected token u in JSON at position 0 at JSON.parse (<anonymous>) 未捕获到的SyntaxError:JSON中的意外令牌&lt;在JSON.parse位置0处( <anonymous> ) - Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>) 语法错误:JSON.parse 中位置 0 处的 JSON 中的意外标记 - SyntaxError: Unexpected token " in JSON at position 0 at JSON.parse Uncaught SyntaxError: Unexpected token & in JSON at position 1 at JSON.parse (<anonymous> )</anonymous> - Uncaught SyntaxError: Unexpected token & in JSON at position 1 at JSON.parse (<anonymous>)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM