作者:几杯茶轶事 | 来源:互联网 | 2023-02-13 19:22
我正在构建一个移动应用程序来显示新闻源.在我的应用程序中,应该能够发布状态.
状态将使用POST方法发送到PHP服务器.
现在我的问题是PHP无法读取我使用angular2发送的POST请求.
这是我的代码:
form.html
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
Firebug控制台:
我似乎无法在这里找到错误.非常感谢您的帮助
1> Igor Jankovi..:
我有同样的问题.你不能像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});