欢迎来到汉中社交动力网络科技有限公司
建站资讯

当前位置: 首页 > 建站资讯 > 建站教程 > PHP教程

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

作者:WAP自助建站 来源:php中文网日期:2025-10-16

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

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

1. PHP 后端 API 准备

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

<?phpheader('Content-Type: application/json'); // 设置响应头为 JSoninterface ReaderInterface{public function read(string $input): OfferCollectionInterface;} interface OfferInterface{}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{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-appcd 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 头部。

<?phpheader('Access-Control-Allow-Origin: *'); // 允许所有来源header('Content-Type: application/json');// ... 你的 PHP 代码 ...?>
登录后复制

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

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

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

知我AI·PC客户端0 查看详情 知我AI·PC客户端

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 请求:

<?phpheader('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培训
上一篇: 在Laravel中高效处理前端JS数组:实现批量数据更新的教程
下一篇: 暂无

推荐建站资讯

更多>