我正在构建一个移动应用来显示新闻Feed。在我的应用程序中,应该能够发布状态。
状态将使用POST方法发送到PHP服务器。
现在我的问题是PHP无法读取我使用angular2发送的POST请求。
这是我的代码:
form.html
<form class="sample-form post-form" [formGroup]="post_form" (ngSubmit)="createStatus()">
<ion-item>
<ion-textarea rows="7" placeholder="What's happening?'" formControlName="status"></ion-textarea>
</ion-item>
<section class="form-section">
<button ion-button block class="form-action-button create-post-button" type="submit" [disabled]="!post_form.valid">Post</button>
</section>
</form>
form.ts
import { Component } from '@angular/core';
import { NavController, AlertController } from 'ionic-angular';
import { Validators, FormGroup, FormControl } from '@angular/forms';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
@Component({
selector: 'form-page',
templateUrl: 'form.html'
})
export class FormLayoutPage {
section: string;
post_form: any;
url: string;
headers: Headers;
constructor(public nav: NavController, public alertCtrl: AlertController, public http: Http) {
this.headers = new Headers();
this.headers.append("Content-Type", "application/x-www-form-urlencoded");
this.section = "post";
this.post_form = new FormGroup({
status: new FormControl('', Validators.required),
});
}
createStatus(){
console.log(this.post_form.value);
this.url = "https://domain.com/mobileREST/poststatus.php";
this.http.post(this.url, this.post_form.value, { headers: this.headers})
.map(res => res.json())
.subscribe(res => {
console.log(res);
},
err => {
console.log(err);
})
}
}
poststatus.php
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
$status = $_POST["status"];
echo json_encode($status);
?>
我似乎无法在这里找到错误。非常感谢您的帮助
答案 0 :(得分:6)
我遇到了同样的问题。您无法像javascript对象一样发送POST参数。你必须像URLSearchParams一样传递它。我已经为你做了一个功能。它将遍历对象并生成URLSearchParam并将其作为字符串返回。
private _buildParams(params: any) {
let urlSearchParams = new URLSearchParams();
for(let key in params){
if(params.hasOwnProperty(key)){
urlSearchParams.append(key, params[key]);
}
}
return urlSearchParams.toString();
}
然后你打电话给http post:
this._http.post(this.url, this._buildParams(params), {headers: this.headers});
答案 1 :(得分:0)
要获取发布的数据,只需在php文件中添加此行
// get posted data
$data = json_decode(file_get_contents("php://input"));