使用 React.js 构建前端并与 PHP 后端交互

心靈之曲
发布: 2025-10-16 09:41:28
原创
384人浏览过

使用 react.js 构建前端并与 php 后端交互

本文旨在指导开发者如何使用 React.js 构建用户界面,并通过 REST API 与 PHP 后端进行数据交互。我们将介绍如何发起 HTTP 请求从 PHP 后端获取数据,并在 React 组件中展示这些数据。文章将提供代码示例,帮助你理解并实现前后端的数据交互。

1. PHP 后端 API 准备

首先,我们需要创建一个 PHP 脚本,它将处理来自前端的请求并返回数据。 以下是一个简单的 PHP 示例,它从 data.json 文件读取数据并返回 JSON 格式的响应。

<?php
header('Content-Type: application/json'); // 设置响应头为 JSON

/**
* The interface provides the contract for different readers
* E.g. it can be XML/JSON Remote Endpoint, or CSV/JSON/XML local files
*/
interface ReaderInterface
{
/**
* Read in incoming data and parse to objects
*/
public function read(string $input): OfferCollectionInterface;
}

 /**
 * Interface of Data Transfer Object, that represents external JSON data
 */
interface OfferInterface
{
}

/**
* Interface for The Collection class that contains Offers
*/
interface OfferCollectionInterface
{
public function get(int $index): OfferInterface;
public function getIterator(): Iterator;
}

/* *********************************** */

class Offer implements OfferInterface
{
public $offerId;
public $productTitle;
public $vendorId;
public $price;


public function __toString(): string
{
    return "$this->offerId | $this->productTitle | $this->vendorId | $this->price\n";
 }
}   

class OfferCollection implements OfferCollectionInterface
{
private $offersList = array();

public function __construct($data)
{
    foreach ($data as $json_object) {
        $offer = new Offer();
        $offer->offerId = $json_object->offerId;
        $offer->productTitle = $json_object->productTitle;
        $offer->vendorId = $json_object->vendorId;
        $offer->price = $json_object->price;

        array_push($this->offersList, $offer);
    }
}

public function get(int $index): OfferInterface
{
    return $this->offersList[$index];
}

public function getIterator(): Iterator
{
    return new ArrayIterator($this->offersList);
}

public function __toString(): string
{
    return implode("\n", $this->offersList);
}
}

class Reader implements ReaderInterface
{
/**
* Read in incoming data and parse to objects
*/
public function read(string $input): OfferCollectionInterface
{
    if ($input != null) {
        $content = file_get_contents($input);
        $json = json_decode($content);
        $result = new OfferCollection($json);

        return $result;
    }

    return new OfferCollection(null);
}
}

class Logger {
private $filename = "logs.txt";

public function info($message): void {
    $this->log($message, "INFO");
}

public function error($message): void {
    $this->log($message, "ERROR");
}

private function log($message, $type): void {
    $myfile = fopen($this->filename, "a") or die("Unable to open file!");
    $txt = "[$type] $message\n";
    fwrite($myfile, $txt);
    fclose($myfile);
}
}

$json_url = 'data.json';

$json_reader = new Reader();
$offers_list = $json_reader->read($json_url);


function count_by_price_range($price_from, $price_to)
{
global $offers_list;
$count = 0;
foreach ($offers_list->getIterator() as $offer) {
    if ($offer->price >= $price_from && $offer->price <= $price_to) {
        $count++;
    }
}
return $count;
}

function count_by_vendor_id($vendorId)
{
global $offers_list;
$count = 0;
foreach ($offers_list->getIterator() as $offer) {
    if ($offer->vendorId == $vendorId) {
        $count++;
    }
}
return $count;
}

$cli_args = $_SERVER['argv'];

$function_name = $cli_args[1];
$logger = new Logger();

switch ($function_name) {
case "count_by_price_range": {
    $logger->info("Getting Count By Price Range From: $cli_args[2] TO $cli_args[3]");
    echo count_by_price_range($cli_args[2], $cli_args[3]);
    break;
}
case "count_by_vendor_id": {
    $logger->info("Getting Count By vendor Id: $cli_args[2]");
    echo count_by_vendor_id($cli_args[2]);
    break;
}
}
$data = array("message" => "Hello from PHP!");
echo json_encode($data);
?>
登录后复制

确保你的 data.json 文件存在,并且包含了有效的 JSON 数据。

2. React.js 前端设置

接下来,创建一个 React 应用。 你可以使用 create-react-app 快速搭建项目:

立即学习PHP免费学习笔记(深入)”;

npx create-react-app my-react-app
cd my-react-app
登录后复制

3. 使用 fetch API 获取数据

在 React 组件中,可以使用 fetch API 向 PHP 后端发起请求。 以下是一个示例组件,它在组件挂载后从 PHP 后端获取数据,并将数据存储在 state 中:

import React, { useState, useEffect } from 'react';

function App() {
  const [message, setMessage] = useState('');

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch('your-php-backend-url.php'); // 替换为你的 PHP 后端 URL
        const data = await response.json();
        setMessage(data.message);
      } catch (error) {
        console.error('Error fetching data:', error);
        setMessage('Failed to load data.');
      }
    };

    fetchData();
  }, []); // 空依赖数组表示只在组件挂载后执行一次

  return (
    <div>
      <h1>{message}</h1>
    </div>
  );
}

export default App;
登录后复制

代码解释:

  • useState 用于声明一个名为 message 的 state 变量,用于存储从 PHP 后端获取的消息。
  • useEffect 用于在组件挂载后执行 fetchData 函数。
  • fetch('your-php-backend-url.php') 发起一个 GET 请求到你的 PHP 后端。 请务必将 'your-php-backend-url.php' 替换为你的实际 URL。
  • response.json() 将响应体解析为 JSON 格式。
  • setMessage(data.message) 将解析后的消息更新到 state 中。
  • 如果在获取数据过程中发生错误,catch 块将捕获错误并在控制台输出错误信息,同时更新 message state 显示错误信息。
  • 空依赖数组 [] 确保 useEffect 只在组件挂载后执行一次。

4. 处理 CORS (跨域资源共享)

如果你的 React 应用和 PHP 后端运行在不同的域名或端口上,你可能会遇到 CORS 问题。 为了解决这个问题,你需要在 PHP 后端设置 CORS 头部。

知我AI·PC客户端
知我AI·PC客户端

离线运行 AI 大模型,构建你的私有个人知识库,对话式提取文件知识,保证个人文件数据安全

知我AI·PC客户端 0
查看详情 知我AI·PC客户端
<?php
header('Access-Control-Allow-Origin: *'); // 允许所有来源
header('Content-Type: application/json');

// ... 你的 PHP 代码 ...
?>
登录后复制

警告: 在生产环境中,强烈建议限制 Access-Control-Allow-Origin 为你的 React 应用的域名,而不是使用 * 允许所有来源。

5. 发送 POST 请求

除了 GET 请求,你还可以使用 fetch API 发送 POST 请求,以便向 PHP 后端传递数据。

import React, { useState } from 'react';

function MyComponent() {
  const [name, setName] = useState('');

  const handleSubmit = async (event) => {
    event.preventDefault();

    try {
      const response = await fetch('your-php-backend-url.php', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ name: name }),
      });

      const data = await response.json();
      console.log(data); // 处理来自 PHP 后端的响应
    } catch (error) {
      console.error('Error sending data:', error);
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input
          type="text"
          value={name}
          onChange={(e) => setName(e.target.value)}
        />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}

export default MyComponent;
登录后复制

PHP 后端处理 POST 请求:

<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
header('Access-Control-Allow-Methods: POST'); // 允许 POST 请求
header('Access-Control-Allow-Headers: Content-Type'); // 允许 Content-Type 头部

$data = json_decode(file_get_contents('php://input'), true);

if (isset($data['name'])) {
  $name = $data['name'];
  $response = array('message' => 'Hello, ' . $name . '!');
  echo json_encode($response);
} else {
  http_response_code(400); // Bad Request
  $response = array('message' => 'Name parameter is missing.');
  echo json_encode($response);
}
?>
登录后复制

代码解释:

  • 在 React 组件中,我们使用 fetch 发起一个 POST 请求,并将数据作为 JSON 字符串包含在请求体中。
  • 在 PHP 后端,我们使用 file_get_contents('php://input') 获取原始的 POST 数据,然后使用 json_decode 将其解析为 PHP 数组。
  • 我们还需要设置 Access-Control-Allow-Methods 头部来允许 POST 请求,并设置 Access-Control-Allow-Headers 允许 Content-Type 头部。

6. 错误处理

在实际应用中,对 API 请求进行适当的错误处理非常重要。 你应该检查响应状态码,并在出现错误时向用户显示友好的错误消息。

import React, { useState, useEffect } from 'react';

function App() {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch('your-php-backend-url.php');
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        const json = await response.json();
        setData(json);
      } catch (e) {
        setError(e);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, []);

  if (loading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  return (
    <div>
      <h1>Data from PHP Backend:</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </div>
  );
}

export default App;
登录后复制

代码解释:

  • 我们添加了 loading 和 error 状态来跟踪 API 请求的状态。
  • 在 try...catch 块中,我们检查 response.ok 来确保响应状态码为 200-299。 如果状态码不在这个范围内,我们抛出一个错误。
  • 在 finally 块中,我们设置 loading 为 false,无论请求成功还是失败。
  • 根据 loading 和 error 状态,我们渲染不同的 UI。

总结

本文介绍了如何使用 React.js 构建前端,并通过 REST API 与 PHP 后端进行数据交互。 我们学习了如何发起 GET 和 POST 请求,如何处理 CORS 问题,以及如何进行错误处理。 通过这些知识,你可以构建功能强大的 Web 应用程序,将 React.js 的前端能力与 PHP 后端的灵活性结合起来。记住,在生产环境中,务必采取适当的安全措施,例如验证用户输入和限制 CORS 来源。

以上就是使用 React.js 构建前端并与 PHP 后端交互的详细内容,更多请关注php中文网其它相关文章!

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号