本文旨在指導(dǎo)開發(fā)者如何使用 React.js 構(gòu)建用戶界面,并通過 REST API 與 PHP 后端進(jìn)行數(shù)據(jù)交互。我們將介紹如何發(fā)起 HTTP 請求從 PHP 后端獲取數(shù)據(jù),并在 React 組件中展示這些數(shù)據(jù)。文章將提供代碼示例,幫助你理解并實(shí)現(xiàn)前后端的數(shù)據(jù)交互。
首先,我們需要創(chuàng)建一個 PHP 腳本,它將處理來自前端的請求并返回數(shù)據(jù)。 以下是一個簡單的 PHP 示例,它從 data.json 文件讀取數(shù)據(jù)并返回 JSON 格式的響應(yīng)。
<?php header('Content-Type: application/json'); // 設(shè)置響應(yīng)頭為 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 數(shù)據(jù)。
接下來,創(chuàng)建一個 React 應(yīng)用。 你可以使用 create-react-app 快速搭建項(xiàng)目:
立即學(xué)習(xí)“PHP免費(fèi)學(xué)習(xí)筆記(深入)”;
npx create-react-app my-react-app cd my-react-app
在 React 組件中,可以使用 fetch API 向 PHP 后端發(fā)起請求。 以下是一個示例組件,它在組件掛載后從 PHP 后端獲取數(shù)據(jù),并將數(shù)據(jù)存儲在 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(); }, []); // 空依賴數(shù)組表示只在組件掛載后執(zhí)行一次 return ( <div> <h1>{message}</h1> </div> ); } export default App;
代碼解釋:
如果你的 React 應(yīng)用和 PHP 后端運(yùn)行在不同的域名或端口上,你可能會遇到 CORS 問題。 為了解決這個問題,你需要在 PHP 后端設(shè)置 CORS 頭部。
<?php header('Access-Control-Allow-Origin: *'); // 允許所有來源 header('Content-Type: application/json'); // ... 你的 PHP 代碼 ... ?>
警告: 在生產(chǎn)環(huán)境中,強(qiáng)烈建議限制 Access-Control-Allow-Origin 為你的 React 應(yīng)用的域名,而不是使用 * 允許所有來源。
除了 GET 請求,你還可以使用 fetch API 發(fā)送 POST 請求,以便向 PHP 后端傳遞數(shù)據(jù)。
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 后端的響應(yīng) } 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); } ?>
代碼解釋:
在實(shí)際應(yīng)用中,對 API 請求進(jìn)行適當(dāng)?shù)腻e誤處理非常重要。 你應(yīng)該檢查響應(yīng)狀態(tài)碼,并在出現(xiàn)錯誤時向用戶顯示友好的錯誤消息。
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 構(gòu)建前端,并通過 REST API 與 PHP 后端進(jìn)行數(shù)據(jù)交互。 我們學(xué)習(xí)了如何發(fā)起 GET 和 POST 請求,如何處理 CORS 問題,以及如何進(jìn)行錯誤處理。 通過這些知識,你可以構(gòu)建功能強(qiáng)大的 Web 應(yīng)用程序,將 React.js 的前端能力與 PHP 后端的靈活性結(jié)合起來。記住,在生產(chǎn)環(huán)境中,務(wù)必采取適當(dāng)?shù)陌踩胧珧?yàn)證用戶輸入和限制 CORS 來源。
以上就是使用 React.js 構(gòu)建前端并與 PHP 后端交互的詳細(xì)內(nèi)容,更多請關(guān)注php中文網(wǎng)其它相關(guān)文章!
PHP怎么學(xué)習(xí)?PHP怎么入門?PHP在哪學(xué)?PHP怎么學(xué)才快?不用擔(dān)心,這里為大家提供了PHP速學(xué)教程(入門到精通),有需要的小伙伴保存下載就能學(xué)習(xí)啦!
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號