[英]Ionic2 create PHP to get data for show in page
我想知道如何创建PHP以获取show home.html的数据
我得到`错误数据未定义
我不知道这是正确的吗? 请检查一下。 我不打算创建PHP,我想设置$ path来保留我的URL。
<ion-content>
<ion-list inset>
<ion-item>
<ion-label>Username</ion-label>
<ion-input [(ngModel)]="data.username" type="text"></ion-input>
</ion-item>
</ion-list>
<div padding>
<button ion-button block (click)="getRepos()">Search</button>
</div>
<ion-card *ngFor="let repo of foundRepos" >
<ion-card-header>
{{ repo.data.name }}
</ion-card-header>
<ion-card-content>
{{ repo.data.description }}
</ion-card-content>
</ion-card>
</ion-content>
。
import { Component } from "@angular/core";
import { NavController } from 'ionic-angular';
import { Http } from '@angular/http';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public foundRepos;
constructor(public http: Http) {
this.data = {}; >>>>>>>data is not defined
data.username = ''; >>>>>data is not defined
this.http = http;
}
getRepos() {
var link = 'http://localhost/github.php';
var data = JSON.stringify({username: this.data.username}); <<<<this.data.username (data is not defined)
this.http.get(link, data) <<<<data is not defined
.subscribe(data => {
this.foundRepos = data.json();
},
err => console.error(err),
() => console.log('getRepos completed')
);
}
}
github.php
<?php
$postdata = file_get_contents("php://input");
if (isset($postdata)) {
$request = json_decode($postdata);
$username = $request->username;
if ($username != "") {
$path = "https://api.github.com/users/".$username."/repos";
echo $path ;
}
else {
echo "Empty username parameter!";
}
}
else {
echo "Not called properly with username parameter!";
}
?>
啊,我明白了。
在您的php中,您正在检索一个名为$postdata
的值。 因此,我假设您要将用户名从ionic 2应用程序发送到您的php文件。
2个选项,您应该同时尝试这两个选项,因为我不了解php,因此不确定是否正确的解决方案。
但我确实知道问题出在哪里。 您正在进行http.get()
调用,并在其中传递了2个参数。 link
和data
。 GET方法用于从链接获取数据,而不是提供数据。 http.get
有两个参数, url
(在您的情况下为link
)和HttpHeaders
对象,而不是 data。
在http.get中带有参数的解决方案
因此,如上所述, http.get()
无法发送您的data
。 除非您将其添加为URL中的参数。 然后,您的打字稿将如下所示(请注意:反引号而不是'',使字符串的合并更容易):
var link = `http://localhost/github.php?username=${this.data.username}`;
this.http.get(link).subscribe(data) { .... }
并在php中替换
$username = $response->username
与
$username = $_GET['username']
所以最终的打字稿看起来像这样(因为php get请求返回了403,Github可能不允许这样做)
getRepos() {
var link = `localhost/…${this.data.username}`;
this.http.get(link)
.subscribe(data => {
let repoUrl = data.text();
this.http.get(repoUrl).subscribe(githubResponse => {
this.foundRepos = githubResponse.json();
});
},
err => console.error(err),
() => console.log('getRepos completed')
);
}
如果有人想详细解释为什么我们得出这个答案,请在下面的聊天窗口中浏览
您尚未在该类中声明数据变量。
export class HomePage {
public foundRepos;
public data;//here
constructor(public http: Http){
this.data = {};
this.data.username = '';//to refer to data in any function always use 'this'
}
//other functions
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.