
本文旨在指导开发者如何使用 React.js 构建用户界面,并通过 REST API 与 PHP 后端进行数据交互。我们将介绍如何发起 HTTP 请求从 PHP 后端获取数据,并在 React 组件中展示这些数据。文章将提供代码示例,帮助你理解并实现前后端的数据交互。
首先,我们需要创建一个 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 数据。
接下来,创建一个 React 应用。 你可以使用 create-react-app 快速搭建项目:
立即学习“PHP免费学习笔记(深入)”;
npx create-react-app my-react-app cd my-react-app
在 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;代码解释:
如果你的 React 应用和 PHP 后端运行在不同的域名或端口上,你可能会遇到 CORS 问题。 为了解决这个问题,你需要在 PHP 后端设置 CORS 头部。
<?php
header('Access-Control-Allow-Origin: *'); // 允许所有来源
header('Content-Type: application/json');
// ... 你的 PHP 代码 ...
?>警告: 在生产环境中,强烈建议限制 Access-Control-Allow-Origin 为你的 React 应用的域名,而不是使用 * 允许所有来源。
除了 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);
}
?>代码解释:
在实际应用中,对 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;代码解释:
本文介绍了如何使用 React.js 构建前端,并通过 REST API 与 PHP 后端进行数据交互。 我们学习了如何发起 GET 和 POST 请求,如何处理 CORS 问题,以及如何进行错误处理。 通过这些知识,你可以构建功能强大的 Web 应用程序,将 React.js 的前端能力与 PHP 后端的灵活性结合起来。记住,在生产环境中,务必采取适当的安全措施,例如验证用户输入和限制 CORS 来源。
以上就是使用 React.js 构建前端并与 PHP 后端交互的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号