1
我是新來的Ionic 3,我想提交他的用戶名數據到MySQL。我使用下面的代碼,它不顯示任何錯誤消息,但它不顯示提交給api.php文件的值。我們如何在下面的api.php文件中使用Insert命令。Ionic 3發佈數據到Mysql
contact.html
<ion-header>
<ion-navbar>
<button ion-button menuToggle>
<ion-icon name="menu"></ion-icon>
</button>
<ion-title>My Contact</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<ion-list>
<ion-item>
<ion-label floating>Username</ion-label>
<ion-input type="text" name="username" [(ngModel)]="data.username"></ion-input>
</ion-item>
<button ion-button color="danger" round (click)="submit()">Submit</button>
<button ion-button color="primary" menuToggle>Toggle Menu</button>
</ion-list>
</ion-content>
contact.ts
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Http } from '@angular/http';
/**
* Generated class for the ContactPage page.
*
* See http://ionicframework.com/docs/components/#navigation for more info
* on Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: 'page-contact',
templateUrl: 'contact.html',
})
export class ContactPage {
data:any = {};
constructor(public navCtrl: NavController, public navParams: NavParams, public http: Http) {
this.data.username = '';
this.data.response = '';
this.http=http;
}
submit() {
var link = '../contact/api.php';
var myData = JSON.stringify({username: this.data.username});
this.http.post(link, myData)
.subscribe(data => {
this.data.response = data["_body"];
}, error => {
console.log("Oooops!");
});
}
ionViewDidLoad() {
console.log('ionViewDidLoad ContactPage');
}
}
api.php
<?php
// Allow from any origin
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, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
echo "You have CORS!";
$postdata = file_get_contents("php://input");
if (isset($postdata)) {
$request = json_decode($postdata);
$username = $request->username;
echo "hello how are you"
if ($username != "") {
echo "Server returns: " . $username;
}
else {
echo "Empty username parameter!";
}
}
else {
echo "Not called properly with username parameter!";
}
?>
請輔助性T o解決問題
我已經從http複製上面的代碼:// WWW。 nikola-breznjak.com/blog/javascript/ionic3/posting-data-ionic-3-app-php-server/,它有工作編輯爲一些用戶 – sahib
這是非常簡單的代碼,所以我想讓它運行,不想在其中做任何重大修改。我認爲從contact.ts文件調用api.php文件存在一些問題(var link ='../contact/api.php';),這個文件可能無法從contact.ts訪問。感謝您的回覆 – sahib