首页 文章

Ionic 2 ajax JSON数据到ngFor

提问于
浏览
0
  • 我有script.php,用mySQL中的数据创建json数组;

  • 下一步 - 我通过AJAX获得了这个json数组;

  • 我想通过ngFor, but I have no idea how I can callback this json array from Ajax success function 在循环中创建div .

感谢帮助!

Home.html

<ion-list *ngFor="let data of displayData" no-lines>
      <ion-item>Text: {{ data.text }} - Value: {{ data.value }}</ion-item>
    </ion-list>

Home.ts - Don't working

import { Component } from '@angular/core';
    import { NavController } from 'ionic-angular';
    import * as $ from 'jquery';

    @Component({
      selector: 'page-home',
      templateUrl: 'home.html'
    })
    export class HomePage {
      pages: string = "app";

      constructor(public navCtrl: NavController) {

      }

      ionViewDidLoad(): any {
        $.ajax({
          type: "GET",
          url: "http://example.com/data.php",
          data: {
            first : "first"
          },
          success: function(data){
           displayData = JSON.parse(data);// Getting JSON
          error: function(data){
            console.log("error");
          }
        })
      }
}

Home.ts - Working

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import * as $ from 'jquery';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  pages: string = "app";
  constructor(public navCtrl: NavController) {

  }
  displayData = [{
    "text": "item 1",
    "value": 1
  },
  {
    "text": "item 2",
    "value": 2
  },
  {
    "text": "item 3",
    "value": 3
  },
  {
    "text": "item 4",
    "value": 4
  },
  {
    "text": "item 5",
    "value": 5
  },
  ];
  ionViewDidLoad(){
    $.ajax({
      type: "GET",
      url: "http://example.com/data.php",
      data: {
        first : "first"
      },
      success: function(data){
        alert("good!");
      },
      error: function(data){
        console.log("error");
      }
    })
  }
}

1 回答

  • 2

    首先,避免使用jQuery . 使用Angular'工具,比如Http客户端 . 然后,将数组设置为displayData .

    export class HomePage {
      pages: string = "app";
      displayData = [];
    
      constructor(public navCtrl: NavController, public http: Http) {
    
      }
    
      ionViewDidLoad(){
        this.http.get('http://niceshot.pro/data.php')
        .map( data => data.json() )
        .subscribe( parsed_data => {
          this.displayData = parsed_data;
        })
    }
    

相关问题