React Native Fetch将数组发送到PHP

时间:2018-03-10 03:29:47

标签: php arrays json reactjs react-native

我是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]

1 个答案:

答案 0 :(得分:0)

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

所以现在我们的问题是解析JSON有效负载,你有两个选择:

第一种方法,使用RecursiveArrayIterator

library(dplyr)
library(purrr)
mget(paste0('file', 1:3)) %>%
     map2_df(., header %>%
                 split(factor(.$filenames, levels = unique(.$filenames))),
                    ~ set_names(.x, .y$label[match(names(.x), .y$num)]))
#   AA  BB    CC
#1 2.3 1.5 202.4
#2 2.1 1.0 200.8
#3 2.1 1.0 208.1

以上代码段的输出(使用Postman):

<?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";
    }
}
?>

解析后你可以保存到数据库(我认为这种方式比下一种方法更繁琐)。

第二种方法:

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

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

第二种方法的输出:

<?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);
?>

最后,希望这个答案可以帮助你:)

仅供参考,使用的参考文献:

第一种方法:

第二种方法:

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

  2. PHP's documentation