douxi0098 2018-04-15 21:16
浏览 68
已采纳

无法处理来自PHP服务和JSON的Ionic HTTP请求

I'm trying to build an Angular-Ionic app, which gets information from a central database via http request information. These are built by PHP in the form of JSON. I also get the information back but can not process it.

My JSON looks like this:

[
   {0: {id: 1, title: 'TITLE', image:'TITEL'},
   {1: {id: 2, title: 'TITLE', image:'TITEL'},
   {2: {id: 3, title: 'TITLE', image:'TITEL'}
]

This is my PHP-Code:

if (isset($_SERVER['HTTP_ORIGIN'])) {
   header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
   header('Access-Control-Allow-Credentials: true');
   header('Access-Control-Max-Age: 86400');    // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {

if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");

if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
    header("Access-Control-Allow-Headers: 
    {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
 }
$mysqli = new mysqli("[DATABASE_URL]", "[DATABASE_USER]", "[DATABASE_PWD]", "[DATABASE]");
$query = "SELECT id, title, image FROM database ORDER BY title ASC";
$dbresult = $mysqli->query($query);

while($row = $dbresult->fetch_array(MYSQLI_ASSOC)){

    $data[] = array(
        'id' => $row['id'],
        'title' => $row['title'],
        'image' => $row['image']
    );
}

if($dbresult){
    $result = json_encode(utf8ize($data),JSON_FORCE_OBJECT);
} else {
    $result = "{success:false}";
}
echo $result;


function utf8ize($d) {
    if (is_array($d)) {
        foreach ($d as $k => $v) {
            $d[$k] = utf8ize($v);
        }
    } else if (is_string ($d)) {
        return utf8_encode($d);
    }
    return $d;
 }

I would like to build a list with the obtained data in Angular / Ionic. I use Ionic 3 on the latest version. Http and HttpClient, as well as HttpProvider did not bring any result:

<ion-card *ngFor="let item of newsData">
  <img src="../../assets/imgs/{{ item.image }}.jpeg"/>
  <div class="card-title">{{ item.title }}</div>
  <div class="card-subtitle">{{item.id}} Rezepte</div> 
</ion-card>

How can I achieve that?

  • 写回答

1条回答 默认 最新

  • douweng7308 2018-04-16 07:43
    关注

    You have to assign the response from your http request to a variable and than just do it the way you did.

    If you give more informations about what you did in ionic to get the response we can see what's the mistake here.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入