简体   繁体   中英

Ionic HTTP request from PHP service with JSON can not be processed

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM