【问题标题】:React Native Fetch sending array to PHPReact Native Fetch 将数组发送到 PHP
【发布时间】:2018-08-18 16:34:46
【问题描述】:

我是 React-Native 和 PHP 的新手,我正在尝试使用如下代码将一个数组从 react-native 发送到我的服务器上的 PHP:

SaveData() {
let { RoomNo } = this.state
let q = [{"0":"BVR001","Stock_Code":"BVR001","1":0,"Qty":0},
         {"0":"BVR015","Stock_Code":"BVR015","1":0,"Qty":0},
         {"0":"BVR017","Stock_Code":"BVR017","1":0,"Qty":0}]

let url = 'http://192.168.100.99/SaveMNB.php'

fetch(url, {
  method : 'POST',
  headers : {
    'Accept' : 'application/json',
    'Content-Type' : 'application/json'
  },
  body : JSON.stringify({
    RoomNo : RoomNo,
    Orderan : q
  })
})
  .then(res => res.json())
  .catch(err => Alert.alert('ERROR',err.toString(),
                [{text: 'OK'}],{ cancelable: false }))
}

在 PHP 端,我的代码如下:

<?php
include("dbconfig.php");

$json = file_get_contents("php://input");

$obj = json_decode($json,true);

$RoomNo = $obj['RoomNo'];
$OrderanX[] = $obj['Orderan'];

$con = sqlsrv_connect($myServer,$MyDbR);
if ( $con === false ) {
    die( print_r( sqlsrv_errors(), true));
}

foreach($OrderanX As $Order) {
    //HERE WILL BE LOOPING THE ARRAY AND PUT IT INTO DATABASE
}

echo json_encode('SUCCESS');

?>

这将始终返回错误,因为我无法将数组从 react-native 传递给 php。

错误是

SyntaxError: JSON Parse error: Unrecognized token '<'

如何将数组从 react-native 传递到 php,谢谢,非常感谢。

编辑:

但是,如果我删除 foreach 循环并将代码更改为

echo json_encode($OrderanX);

它会返回

[object Object],[object Object].[object Object]

【问题讨论】:

  • 请添加它返回的错误。
  • 之前在浏览器网络控制台中检查您的响应。
  • 已经添加错误信息,请帮忙

标签: php arrays json reactjs react-native


【解决方案1】:

首先,您的 react 本机代码表现良好 :)

所以现在我们的问题在于解析 JSON 有效负载,您有两种选择:

第一种方法,使用RecursiveArrayIterator:

<?php
$json = file_get_contents("php://input");
$jsonIterator = new RecursiveIteratorIterator(
    new RecursiveArrayIterator(json_decode($json, TRUE)),
    RecursiveIteratorIterator::SELF_FIRST);

foreach ($jsonIterator as $key => $val) {
    if(is_array($val)) {
        echo "$key:\n";
    } else {
        echo "$key => $val\n";
    }
}
?>

上面代码sn-p的输出(使用Postman):

RoomNo => 1
Orderan:
0:
0 => BVR001
1 => 0
Stock_Code => BVR001
Qty => 0
1:
0 => BVR015
1 => 0
Stock_Code => BVR015
Qty => 0
2:
0 => BVR017
1 => 0
Stock_Code => BVR017
Qty => 0

解析后可以保存到数据库(我觉得这种方式会比next方式繁琐)。


第二种方法:

按照您的方式解析 JSON,但稍作更改(更改了对象属性的访问方法):

<?php
$json = file_get_contents("php://input");

$obj = json_decode($json);

$RoomNo = $obj->RoomNo;

//Removed the [] as there is no need to define an object like this!
//It is already an array
//To define new empty array use: $varName = array()
$OrderanX = $obj->Orderan;

$response = array();
foreach($OrderanX As $Order) {
    //HERE WILL BE LOOPING THE ARRAY AND PUT IT INTO DATABASE
    // Save these variables to your database
    $zero = $Order->{'0'};
    $one = $Order->{'1'};
    $stockCode = $Order->Stock_Code;
    $stockQty = $Order->Qty;
    $stockItem=array(
        "0" => $zero,
        "1" => $one,
        "stock_code" => $stockCode,
        "qty" => $stockQty
    );
    array_push($response, $stockItem);
}

echo json_encode($response);
?>

第二种方法的输出:

[
    {
        "0": "BVR001",
        "1": 0,
        "stock_code": "BVR001",
        "qty": 0
    },
    {
        "0": "BVR015",
        "1": 0,
        "stock_code": "BVR015",
        "qty": 0
    },
    {
        "0": "BVR017",
        "1": 0,
        "stock_code": "BVR017",
        "qty": 0
    }
]

最后,希望这个答案对你有帮助:)

仅供参考,使用的参考资料:

第一种方法:

第二种方法:

  1. How to access object properties with names like integers?

  2. PHP's documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多