简体   繁体   English

从 PHP 获取数据的 JavaScript 问题

[英]JavaScript problem with fetching data from PHP

I'm new to PHP, and i'm trying to fetch data from PHP to JavaScript.我是 PHP 新手,正在尝试从 PHP 获取数据到 JavaScript。 When i do that, JavaScript always giving me the same error "Unexpected token < in JSON at position 0".当我这样做时,JavaScript 总是给我同样的错误“Unexpected token < in JSON at position 0”。 I don't have any idea what to do.我不知道该怎么办。 I'm stuck...Help Help !我被卡住了...帮助 帮助! x) X)

There is the code有代码

JavaScript JavaScript

 var xmlhttp = new XMLHttpRequest();

 xmlhttp.onreadystatechange = function () {
 if (this.readyState == 4 && this.status == 200) {
    var myObj = JSON.parse(this.responseText);
    document.getElementById("demo").innerHTML = myObj.name;
  }
 };

xmlhttp.open("GET", "data.php", true);
xmlhttp.send();

PHP PHP

<?php
  $myObj->name = "John";
  $myObj->age = 30;
  $myObj->city = "New York";

  $myJSON = json_encode($myObj);

  echo $myJSON;

?> ?>

I think you are getting an issue of object我认为您遇到了对象问题
Object $myObj need to be initialized before using it对象 $myObj 需要在使用前初始化
I have updated the code (Initialized the object) please use the below code on php page to resolve the issue我已更新代码(初始化对象)请在 php 页面上使用以下代码来解决问题

<?PHP
  $myObj = new StdClass();
  $myObj->name = "John";
  $myObj->age = 30;
  $myObj->city = "New York";

  $myJSON = json_encode($myObj);

  echo $myJSON; 

Obviously, the response returned for your XMLHttpRequest is not a valid JSON .显然,为您的 XMLHttpRequest 返回的响应不是有效的 JSON Provided that your PHP codesample is complete, PHP will most likely(*) echo an E_WARNING error before outputting the JSON string, although your code will work.假设您的 PHP 代码示例是完整的,PHP 很可能会 (*) 在输出 JSON 字符串之前回显E_WARNING错误,尽管您的代码可以工作。 Related question and solution here .相关问题和解决方案在这里 Easiest way to check is to view the raw response in your browser's dev tools (supported by all major browsers).最简单的检查方法是在浏览器的开发工具(所有主要浏览器都支持)中查看原始响应。 If the response contains anything except the JSON string, JSON.parse() will throw an error.如果响应包含除 JSON 字符串之外的任何内容, JSON.parse()将抛出错误。

(*)This depends on your error reporting settings (*)这取决于您的错误报告设置

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM