Angular2 http.post表单值到php服务器

前端之家收集整理的这篇文章主要介绍了Angular2 http.post表单值到php服务器前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试将表单值从Ionic2(Angular2 typescript)项目发送到我将发送联系邮件PHP服务器.

我无法得到我应该得到的价值……

这是我的form.service.ts:

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());
  }
}

我的form.ts中的onSubmit函数使用了哪个:

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' },label: 'Recommandation' },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.@R_301_103@,Validators.minLength(3),this.checkFirstCharacterValidator])],prenom: ['',Validators.compose([Validators.minLength(3),company: ['',projet: ['',Validators.@R_301_103@],arrivee: ['',phone: ['',Validators.minLength(10)])],email: ['',website: ['',Validators.minLength(3)],message: ['',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)
      );
  }
}

在我的email.PHP文件中,我正在尝试获取POST:

<?PHP
header('Content-type: application/json');

    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);
    }

$value = json_decode(file_get_contents('PHP://input'));

// for test     
echo $value->name;

?>

我检查了chrome的控制台,我得到了一些东西:
Screenshot from console

我怎样才能将angular2的帖子发送到我的PHP中?我错过了什么吗?

我可以在你的代码中看到两个问题:

>使用JSON.stringify创建JSON内容但是对于表单,您需要使用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());
}
原文链接:https://www.f2er.com/angularjs/142168.html

猜你在找的Angularjs相关文章