我正在尝试将表单值从Ionic2(Angular2 typescript)项目发送到我将发送联系邮件的php服务器。
我无法得到我应该得到的价值......
这是我的form.service.ts:
<br />
<b>Fatal error</b>: Uncaught exception 'Google_Service_Exception' with message 'Error calling DELETE
https://www.googleapis.com/calendar/v3/calendars/cnhkehagcve7rm8s1g88hauer8%40group.calendar.google.com/events/97smpf2320s3lmg8nnnpb9dndc: (410)
Resource has been deleted' in
/var/www/html/prototipo/application/third_party/vendor/google/apiclient/src/Google/Http/REST.php:110
在我的form.ts中使用了我的onSubmit函数:
import {Injectable} from 'angular2/core';
import {Http, Response} from 'angular2/http';
import {Headers, RequestOptions} from 'angular2/http';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class FormService {
constructor (private _http: Http) {}
private _contactUrl = 'http://localhost:8888/Server/email.php';
// private _contactUrl = '/email';
sendMail(value: Object): Observable<any> {
const body = JSON.stringify(value);
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-urlencoded');
return this._http.post(this._contactUrl, body, {
headers : headers
}).map(res => res.json());
}
}
在我的email.php文件中,我正在尝试获取POST:
import { Page, NavController } from 'ionic-angular';
import { Component } from 'angular2/core';
import { FORM_DIRECTIVES, FormBuilder, ControlGroup, Validators, AbstractControl } from 'angular2/common';
import { Http, Response, Headers } from 'angular2/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import { FormService} from './form.service';
@Page({
templateUrl: 'build/pages/form/form.html',
directives: [FORM_DIRECTIVES],
providers: [FormService]
})
export class Form {
contactForm: ControlGroup;
company: AbstractControl;
name: AbstractControl;
prenom: AbstractControl;
phone: AbstractControl;
email: AbstractControl;
website: AbstractControl;
message: AbstractControl;
arrivee: AbstractControl;
projet: AbstractControl;
projets = [
{ id: 1, label: 'Site Internet' },
{ id: 2, label: 'Site Intranet/Extranet' },
{ id: 3, label: 'Développement PHP' },
{ id: 4, label: 'Développement C#' },
{ id: 5, label: 'Conception Base de Données' },
{ id: 6, label: 'Tiers Maintenance Applicative' },
{ id: 7, label: "Recrutement d'un collaborateur Handicapé" }
];
arrivees = [
{ id: 1, label: 'Internet' },
{ id: 2, label: 'Recommandation' },
{ id: 3, label: 'Evênement' }
];
response: string;
value: any;
constructor(public nav: NavController, fb: FormBuilder, private _http: Http, private _formService: FormService) {
this.nav = nav;
// New controlGroup instance
this.contactForm = fb.group({
// Validators Rules for each field
// Champ XXX: ['', ...] correspondants au [ngFormControl]="XXX" de la vue HTML (inpput)
name: ['', Validators.compose([Validators.required, Validators.minLength(3), this.checkFirstCharacterValidator])],
prenom: ['', Validators.compose([Validators.minLength(3), this.checkFirstCharacterValidator])],
company: ['', Validators.compose([Validators.required, Validators.minLength(3), this.checkFirstCharacterValidator])],
projet: ['', Validators.required],
arrivee: ['', Validators.required],
phone: ['', Validators.compose([Validators.required, Validators.minLength(10)])],
email: ['', Validators.required],
website: ['', Validators.minLength(3)],
message: ['', Validators.compose([Validators.required, Validators.minLength(20)])]
});
this.name = this.contactForm.controls['name'];
this.prenom = this.contactForm.controls['prenom'];
this.company = this.contactForm.controls['company'];
this.projet = this.contactForm.controls['projet'];
this.arrivee = this.contactForm.controls['arrivee'],
this.phone = this.contactForm.controls['phone'],
this.email = this.contactForm.controls['email'],
this.website = this.contactForm.controls['website'],
this.message = this.contactForm.controls['message']
}
// Check if firt character is a number
checkFirstCharacterValidator(control: Control): { [s: string]: boolean } {
if (control.value.match(/^\d/)) {
return { checkFirstCharacterValidator: true };
}
}
onSubmit(value) {
this._formService.sendMail({value})
.subscribe(
response => this.response = response,
error => console.log(error)
);
}
}
我检查了chrome的控制台,我得到了一些东西: Screenshot from console
如何从angular2获取帖子到我的php中?我错过了什么吗?
答案 0 :(得分:8)
我可以在您的代码中看到两个问题:
URLSearchParams
类或手动创建字符串内容。application/x-www-form-urlencoded
而不是application/x-www-urlencoded
。以下是您应该使用的内容:
sendMail(value: Object): Observable<any> {
const body = new URLSearchParams();
Object.keys(value).forEach(key => {
body.set(key, value[key]);
}
let headers = new Headers();
headers.append('Content-Type',
'application/x-www-form-urlencoded');
return this._http.post(this._contactUrl, body.toString(), {
headers : headers
}).map(res => res.json());
}
答案 1 :(得分:4)
我设法让它工作,它只是:
sendMail(value: any): Observable<any> {
const body = new URLSearchParams(value);
body.set('name', value.name);
body.set('company', value.company);
body.set('projet', value.projet);
body.set('arrivee', value.arrivee);
body.set('phone', value.phone);
body.set('email', value.email);
body.set('website', value.website);
body.set('message', value.message);
body.set('name', value.name);
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
return this._http.post(this._contactUrl, body.toString(), {
headers : headers
}).map(res => res.json());
}
在form.php中:
<?php header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
$formData = json_decode(file_get_contents('php://input'));
foreach ($formData as $key=>$value) {
$_POST[$key]=$value;
}
$formObject = $_POST['name'];
(...) ?>
感谢Thierry Templier的宝贵帮助。
答案 2 :(得分:1)
也许对某人有用。我遇到嵌套对象的问题 - 传递给这样的PHP对象:
var obj = {
value: 1,
innerObj: {
title: "title",
innerObject: {
value: 1
}
}
};
解决了这个问题
使用示例:
//at top of you .ts file
let qs = require('qs');
return this.http.post(url, qs.stringify(data), {headers: this.postHeader})
.map((resp: Response) => resp.json())
.catch((error: any) => Observable.throw(error) || 'Server error');
对于非嵌套对象
也很有用