php - 将 json 文件从 php 连接到 ReactJs

标签 php json ajax reactjs

请帮帮我。我有一个在 php 中生成的 json 文件。我需要通过ajax将文件传输到React js组件中。但出了点问题。控制台写json错误,但是json是自动生成的。谢谢!

我的代码reactjs:

/*var data = [
{type: 1, tempFrom: "+5", tempTo: "+8"},
{type: 2, tempFrom: "+5", tempTo: "+8"},
{type: 3, tempFrom: "+5", tempTo: "+8"},
{type: 4, tempFrom: "+5", tempTo: "+8"}
];*/


var WeatherItem = React.createClass({
 render: function() {
  return (
   <div className="weatherItem">
    <h2 className="weatherCity">
     {this.props.city}
    </h2>
    {this.props.children}
  </div>
  );
 }
});

var WeatherBox = React.createClass({
 getInitialState: function() {
  return {data: []};
 },
componentDidMount: function() {
 $.ajax({
  url: this.props.url,
  dataType: 'json',
  cache: false,
  success: function(data) {
    this.setState({data: data});
  }.bind(this),
  error: function(xhr, status, err) {
    console.error(this.props.url, status, err.toString());
  }.bind(this)
});
},
render: function() {
 return (
  <div className="wetherBox">
  <h1> Weather</h1>
  <WeatherForm />
  <WeatherList data={this.state.data} />
  </div>
  );
 }
 });

 var WeatherList = React.createClass({
  render: function() {
   var weatherNodes = this.props.data.map(function(weatherItem){
    return (
     <WeatherItem city = {weatherItem.city} key = {weatherItem.id}>
     {weatherItem.text}</WeatherItem>
    );
  });
  return (
   <div className="weatherList">
    {weatherNodes}
   </div>
  );
 }
});

var WeatherForm = React.createClass({
 render: function() {
  return (
  <div className="weatherForm">
   Hello, world! I am a WeatherForm.
  </div>
  );
}
});

ReactDOM.render(
<WeatherBox url="weather.php" />,
document.getElementById('content')
);

PHP:

<?php
$city = $_POST["city_id"];

$data_file = 'https://export.yandex.ru/bar/reginfo.xml?region='.$city.'.xml';   // загружаем файл прогноза погоды для выбранного города
$xml = simplexml_load_file($data_file); // загружаем xml файл через simple_xml

foreach($xml->weather->day as $day){

  foreach($day->day_part as $day_part):
   $img = strval($day_part->{'image-v2'});
   $tempFrom = strval($day_part->temperature_from);
  $tempTo = strval($day_part->temperature_to);

  $attrs = $day_part->attributes();
  $type= strval($attrs['type']);

  echo json_encode(array("type"=>$type, "src"=>$img, "tempFrom"=>$tempFrom, "tempTo"=>$tempTo));

  endforeach;
}

Error

enter image description here

最佳答案

尝试在您的响应中添加 header 以指示是 JSON 内容,通过数组回显结果将不是有效的 JSON,以这种方式重构您的代码:

<?php

$city = $_POST["city_id"];

$data_file = 'https://export.yandex.ru/bar/reginfo.xml?region='.$city.'.xml';   // загружаем файл прогноза погоды для выбранного города
$xml = simplexml_load_file($data_file); // загружаем xml файл через simple_xml

$result = array();

foreach($xml->weather->day as $day){

  foreach($day->day_part as $day_part):
   $img = strval($day_part->{'image-v2'});
   $tempFrom = strval($day_part->temperature_from);
  $tempTo = strval($day_part->temperature_to);

  $attrs = $day_part->attributes();
  $type= strval($attrs['type']);
  $result[] = array("type"=>$type, "src"=>$img, "tempFrom"=>$tempFrom, "tempTo"=>$tempTo);

  endforeach;
}

header('Content-Type: application/json');
echo json_encode($result);

关于php - 将 json 文件从 php 连接到 ReactJs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40617807/

相关文章:

php - 从字符串中删除特定模式

php - 如何限制MySQL数据库的条目数?

java - 将没有特定标准结构的 JSON 解析为 Map 或 Java 对象

javascript - javascript 函数中出现错误 - "chartobject-1.render() Error >> Unable to find the container DOM element."

javascript - 检测多个异步 javascript $.ajax 调用的完成

javascript - 为 JavaScript 提供按钮的 id

php - 异常 'PDOException',消息为“SQLSTATE[HY093] : Invalid parameter number: number of bound variables does not match number of tokens”

javascript - 使用设计随机化屏幕上的文本

javascript - 如何将变量传递到 JSON 搜索循环?

javascript - Django:如何将 javascript var 作为 ajax 中的参数传递给 Django URL?