如何从php中获取数组来响应axios?

kknvjkwl  于 2023-01-05  发布在  iOS
关注(0)|答案(1)|浏览(148)
Array
(
    [0] => Array
        (
            [images] => projects/0mxlk1duzt/1.png
        )

    [1] => Array
        (
            [images] => projects/0mxlk1duzt/2.png
        )

    [2] => Array
        (
            [images] => projects/0mxlk1duzt/3.png
        )
)

这是数组什么我在PHP文件在服务器上,代码在PHP

<?php
    header('Access-Control-Allow-Origin: *');
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
    header("Access-Control-Allow-Headers: Content-Disposition, Content-Type, Content-Length, Accept-Encoding");
    header("Content-type:application/json");

$response = array();
    foreach(glob('projects/0mxlk1duzt/*', GLOB_NOSORT) as $image)   
    {  
                  array_push($response,array(
                    "images" => $image
                  ));
    }  
    print_r($response); 
?>

接下来,我有React应用程序与axios与代码:

class Gallery extends React.Component {
  state = {
    images: []
  }
  componentDidMount() {
    const url = 'http://work.eniso.ru/gallery.php'
    axios.get(url).then(response => response.data)
    .then((data) => {
      this.setState({ images: data })
      console.log(this.state.images)
     })
  }
  render(){
    return(
      <div className='gallery'>
        <ul>
          { this.state.images }
        </ul>
      </div>
    )
  }
}

现在我只能以文本格式输出,但我不知道如何获得数组,在react中,我必须执行array.map以<li><li>输出元素

brgchamk

brgchamk1#

在PHP中我需要做:

echo json_encode($response);

在React中,我需要array.map

{ this.state.images.map((response, i) => (
 <div key={i}>
  <img className='img-prew' src={response.images} />
 </div>
))}

相关问题