亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

搜索

使用 React.js 構(gòu)建前端并與 PHP 后端交互

心靈之曲
發(fā)布: 2025-10-16 09:41:28
原創(chuàng)
369人瀏覽過

使用 react.js 構(gòu)建前端并與 php 后端交互

本文旨在指導(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ù)交互。

1. PHP 后端 API 準(zhǔn)備

首先,我們需要創(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);
?>
登錄后復(fù)制

確保你的 data.json 文件存在,并且包含了有效的 JSON 數(shù)據(jù)。

2. React.js 前端設(shè)置

接下來,創(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
登錄后復(fù)制

3. 使用 fetch API 獲取數(shù)據(jù)

在 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;
登錄后復(fù)制

代碼解釋:

  • useState 用于聲明一個名為 message 的 state 變量,用于存儲從 PHP 后端獲取的消息。
  • useEffect 用于在組件掛載后執(zhí)行 fetchData 函數(shù)。
  • fetch('your-php-backend-url.php') 發(fā)起一個 GET 請求到你的 PHP 后端。 請務(wù)必將 'your-php-backend-url.php' 替換為你的實(shí)際 URL。
  • response.json() 將響應(yīng)體解析為 JSON 格式。
  • setMessage(data.message) 將解析后的消息更新到 state 中。
  • 如果在獲取數(shù)據(jù)過程中發(fā)生錯誤,catch 塊將捕獲錯誤并在控制臺輸出錯誤信息,同時更新 message state 顯示錯誤信息。
  • 空依賴數(shù)組 [] 確保 useEffect 只在組件掛載后執(zhí)行一次。

4. 處理 CORS (跨域資源共享)

如果你的 React 應(yīng)用和 PHP 后端運(yùn)行在不同的域名或端口上,你可能會遇到 CORS 問題。 為了解決這個問題,你需要在 PHP 后端設(shè)置 CORS 頭部。

<?php
header('Access-Control-Allow-Origin: *'); // 允許所有來源
header('Content-Type: application/json');

// ... 你的 PHP 代碼 ...
?>
登錄后復(fù)制

警告: 在生產(chǎn)環(huán)境中,強(qiáng)烈建議限制 Access-Control-Allow-Origin 為你的 React 應(yīng)用的域名,而不是使用 * 允許所有來源。

知我AI·PC客戶端
知我AI·PC客戶端

離線運(yùn)行 AI 大模型,構(gòu)建你的私有個人知識庫,對話式提取文件知識,保證個人文件數(shù)據(jù)安全

知我AI·PC客戶端0
查看詳情 知我AI·PC客戶端

5. 發(fā)送 POST 請求

除了 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;
登錄后復(fù)制

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);
}
?>
登錄后復(fù)制

代碼解釋:

  • 在 React 組件中,我們使用 fetch 發(fā)起一個 POST 請求,并將數(shù)據(jù)作為 JSON 字符串包含在請求體中。
  • 在 PHP 后端,我們使用 file_get_contents('php://input') 獲取原始的 POST 數(shù)據(jù),然后使用 json_decode 將其解析為 PHP 數(shù)組。
  • 我們還需要設(shè)置 Access-Control-Allow-Methods 頭部來允許 POST 請求,并設(shè)置 Access-Control-Allow-Headers 允許 Content-Type 頭部。

6. 錯誤處理

在實(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;
登錄后復(fù)制

代碼解釋:

  • 我們添加了 loading 和 error 狀態(tài)來跟蹤 API 請求的狀態(tài)。
  • 在 try...catch 塊中,我們檢查 response.ok 來確保響應(yīng)狀態(tài)碼為 200-299。 如果狀態(tài)碼不在這個范圍內(nèi),我們拋出一個錯誤。
  • 在 finally 塊中,我們設(shè)置 loading 為 false,無論請求成功還是失敗。
  • 根據(jù) loading 和 error 狀態(tài),我們渲染不同的 UI。

總結(jié)

本文介紹了如何使用 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é)教程(入門到精通)
PHP速學(xué)教程(入門到精通)

PHP怎么學(xué)習(xí)?PHP怎么入門?PHP在哪學(xué)?PHP怎么學(xué)才快?不用擔(dān)心,這里為大家提供了PHP速學(xué)教程(入門到精通),有需要的小伙伴保存下載就能學(xué)習(xí)啦!

下載
來源:php中文網(wǎng)
本文內(nèi)容由網(wǎng)友自發(fā)貢獻(xiàn),版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請聯(lián)系admin@php.cn
最新問題
開源免費(fèi)商場系統(tǒng)廣告
最新下載
更多>
網(wǎng)站特效
網(wǎng)站源碼
網(wǎng)站素材
前端模板
關(guān)于我們 免責(zé)申明 意見反饋 講師合作 廣告合作 最新更新
php中文網(wǎng):公益在線php培訓(xùn),幫助PHP學(xué)習(xí)者快速成長!
關(guān)注服務(wù)號 技術(shù)交流群
PHP中文網(wǎng)訂閱號
每天精選資源文章推送
PHP中文網(wǎng)APP
隨時隨地碎片化學(xué)習(xí)
PHP中文網(wǎng)抖音號
發(fā)現(xiàn)有趣的

Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號