You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native中如何提取返回数组的文本内容并转为字符串

从数据库响应数组中提取纯文本内容的实现方案

问题根因

当前返回结果存在冗余的原因有两点:

  • PHP端使用mysqli_fetch_array取数时,默认会同时返回数字索引、字符串关联索引的重复字段,且循环终止时会向数组追加一个空的false值,导致返回结构冗余
  • 前端直接打印整个响应结构,没有做字段提取和空值过滤

修复方案

1. 服务端PHP代码优化(优先推荐)

从数据源层面清理冗余,同时修复原代码存在的POST参数未读取、SQL注入风险问题:

<?php
include('db.php');
// 读取前端传入的JSON格式POST参数
$postRaw = file_get_contents('php://input');
$decodedData = json_decode($postRaw, true);
$Username = $decodedData['Username'];

// 预处理SQL语句,避免SQL注入风险
$stmt = mysqli_prepare($conn, "SELECT text FROM scanned WHERE username = ?");
mysqli_stmt_bind_param($stmt, "s", $Username);
mysqli_stmt_execute($stmt);
$queryResult = mysqli_stmt_get_result($stmt);

$textArr = [];
// 循环仅读取关联数组,无数据时自动终止,不会追加空值
while($row = mysqli_fetch_assoc($queryResult)){
    $textArr[] = $row['text']; // 直接存储text字段的纯文本内容
}

echo json_encode($textArr);
?>

2. 前端JS代码调整

服务端优化后返回值为纯文本组成的一维数组,可直接遍历输出:

function getItem(username){
    const InsertAPIURL = "http://192.168.0.87/AM_LOGIN/getScanned.php";

    const headers = {
        Accept: "application/json",
        "Content-Type": "application/json",
    };

    const reqData = {
        Username: username,
    };

    fetch(InsertAPIURL, {
        method: "POST",
        headers: headers,
        body: JSON.stringify(reqData),
    })
    .then(response => response.json())
    .then(textList => {
        // 打印全部文本数组
        console.log("查询到的全部文本:", textList);
        // 逐条打印单条文本
        textList.forEach((content, idx) => {
            console.log(`第${idx + 1}条内容:${content}`);
        })
    })
    .catch(error => {
        alert("[BŁĄD]" + error);
    });
}

临时兼容方案(不修改PHP代码)

如果暂时无法调整服务端代码,可直接在前端对返回结果做过滤提取:

.then(response => {
    const textList = response
        // 过滤掉末尾的空值
        .filter(item => item)
        // 提取每条记录的text字段
        .map(item => item.text);
    console.log("提取后的纯文本:", textList);
})

注意:该方案仅做前端兼容,原PHP代码存在SQL注入漏洞,建议尽快按前述方案修复服务端逻辑。


内容的提问来源于stack exchange,提问作者Taco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.03 05:15:55