我想知道如何创建 PHP 来获取 show home.html 的数据
and I get `Error data is not defined
我不知道这对吗?请检查这个。我不知道创建 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 文件。
两个选项,你应该尝试它们,因为我不懂 php,所以我不确定正确的解决方案是什么。
但我确实知道问题出在哪里。您正在进行 http.get()
调用,并在其中传递 2 个参数。 链接
和数据
。 GET 方法用于从链接获取数据,而不是提供数据。 http.get
需要 2 个参数,url
(在您的例子中名为 link
)和一个 HttpHeaders
对象,所以不是数据。
解决方案,http.get 中带有参数
因此,如上所述,http.get()
无法发送您的数据
。除非您将其作为参数添加到 URL 中。那么你的 typescript 将如下所示(注意:反引号而不是“”,使字符串连接更容易):
var link = `http://localhost/github.php?username=${this.data.username}`;
this.http.get(link).subscribe(data) { .... }
并在 php 中替换
$username = $response->username
与
$username = $_GET['username']
最终的 typescript 看起来像这样(因为 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')
);
}
如果有人想要详细解释我们为什么得出这个答案,请查看下面的聊天
关于javascript - Ionic2 创建 PHP 来获取数据以在页面中显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41842308/