【问题标题】:Send Json from PHP to React Native从 PHP 发送 Json 到 React Native
【发布时间】:2020-02-07 19:46:13
【问题描述】:

所以我有一个 josn 对象,它有一个对象数组,我想通过 https 发送到 react native 应用程序,但问题是我在 react native 中得到 null

php的代码:

<?php
class Product {
    // Properties
    public $title;
    public $price; 
  }
header('Content-Type: application/json');
$ProductList =array();
$aa=$a->{'shopping_results'};
foreach($aa as $y => $y_value) {
    $product = new Product();
   $product->{'title'} =  $y_value ->{'title'};
   $product->{'price'} = $y_value ->{'price'};
    array_push($ProductList,$product);
}
echo $x=json_encode(array('listx' => $ProductList),JSON_UNESCAPED_UNICODE);// the JSON_UNESCAPED_UNICODE for the Arabic letters
?>

当我尝试在浏览器上查看这个 json 的内容时,这就是我得到的 https://i.stack.imgur.com/gXT4X.png

The react native code

 await fetch(URL, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json'
            }
            // , body: JSON.stringify({ name: "tea" })
        })
            .then((response) => response.text()) //tried .json() got JSON Parse error: Unexpected EOF
            .then((responseJson) => {
                console.log(responseJson);//This prints blank
                console.log("hi");

                this.setState({ output: responseJson });//nothing shows

            })
            .catch((error) => {
                console.error(error);
            });

注意:我尝试接收来自 HTTPs 请求的文本并且它有效(连接正常)

【问题讨论】:

  • 为什么echo $x=json_encode... 中有$x= 部分?
  • response.data 通常是 json 所在的位置
  • 我这样做是因为我想尝试解码 json 它只是为了测试编码是否正确
  • 删除$x=,它没有增加任何好处,并且可能有问题(不是100%肯定)
  • @DCTID 没有所谓的数据我试过了,但是没用

标签: php json react-native


【解决方案1】:

您需要在 PHP 代码中设置 HTTP 标头和方法,以便接受来自您的 react 本机应用程序的请求(基本上我是在告诉您实现 REST API)。如果已经实现,只需确保在 react-native 的 fetch URL 中提供正确的端点。还有一件事,当您尝试从服务器检索数据时,请确保设置方法:'GET'。

如果您是初学者/没有关于 REST API 的先验知识,那么这里有一个参考供您参考:https://www.positronx.io/create-simple-php-crud-rest-api-with-mysql-php-pdo/ 我相信它会给您一些关于您的需求的基本概念。

【讨论】:

猜你喜欢
  • 2018-08-18
  • 2021-10-13
  • 1970-01-01
  • 1970-01-01
  • 2021-04-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多