繁体   English   中英

从angular2 +到php的Http.post表单数据

[英]Http.post form data from angular2+ to php

我已经花了几个小时寻找SO,但是我找不到任何试图做我自己的人。 我正在尝试使用http.post通过Angular从HTML表单向PHP发送(数组)数据。 当我尝试执行此操作时,它会将PHP文件中的硬编码值发送到PostgreSQL,但是我不确定Angular是否将数据发送到PHP还是我没有正确访问$ _POST变量。

这是我现在拥有的代码:

寄存器form.component.html:

<div class="container">
  <h1>Sign Up</h1>
  <h5>Items marked with a * are required.</h5> <br>
  <form (ngSubmit)="onSubmit(model)" #registerForm="ngForm">
    <div class="form-group">
      <label for="username">Username *</label>
      <input type="text" class="form-control width" id="username" required [(ngModel)]="model.username" name="account[username]"
                                                                                                    #username = "ngModel">
      <div [hidden]="username.valid || username.untouched" class="alert alert-danger">
        Username is required
      </div>
    </div>
    <div class="form-group">
      <label for="password">Password *</label>
      <input type="text" class="form-control width" id="password" minlength="6" required [(ngModel)]="model.password"
                                                                              name="account[password]" #password = "ngModel">
      <div [hidden]="password.valid || password.untouched" class="alert alert-danger">
        Password is required and must be at least 6 characters
      </div>
    </div>
    <div class="form-group">
      <label for="email">E-mail *</label>
      <input type="text" class="form-control width" id="email" required [(ngModel)]="model.email" name="account[email]"
                                                                                              #email = "ngModel" pattern="^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$">
      <div [hidden]="!email.hasError('pattern') || email.untouched" class="alert alert-danger">
        E-mail is required and must be a valid e-mail
      </div>
    </div>
    <div class="form-group">
      <label for="phoneNumber">Phone Number</label>
      <input type="text" pattern="[0-9]*" class="form-control width" minlength="10" maxlength="10" id="phoneNumber"
                                            name="account[phone]" [(ngModel)]="model.phoneNumber" #number = "ngModel">
      <div [hidden]="number.pristine">
        <div [hidden]="!number.hasError('minlength')" class="alert alert-danger">Phone number should only have 10 digits in xxxxxxxxxx format.</div>
        <div [hidden]="!number.hasError('pattern')" class="alert alert-danger">Phone number should only have digits.</div>
      </div>
    </div>
    <input type="submit" class="btn btn-success"[disabled]="!registerForm.form.valid" value="Submit">
  </form>
</div>

寄存器form.component.ts:

import { Component, OnInit } from '@angular/core';
import { user } from '../user';
import { Http, HttpModule, Response } from '@angular/http';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-register-form',
  templateUrl: './register-form.component.html',
  styleUrls: ['./register-form.component.css']
})
export class RegisterFormComponent implements OnInit {

  constructor(private http: Http) { }

  model = new user('','','','');

  ngOnInit() { }

  submitted = false;

  onSubmit(...event: user[]) {
    this.submitted = true;
    console.log(event); //just for testing - outputs inputted data from form into console
    console.log(event[0]); //same as above
    var test = this.http.post('http://localhost/register-form-component.php', event[0]); //should this just be 'event'?
    test.subscribe();
  }

}

寄存器外形component.php:

<?php
    $dbconn = pg_connect("host=localhost port=5432 dbname=sample user=sample password=sample");
    if(!$dbconn) {
      echo "connection failed";
      exit;
    }
    $test = ["testuser","testpass132","example@gmail.com",1234566543];
    $values = [$_POST['username'], $_POST['password'], $_POST['email'], $_POST['phoneNumber']];
    $result = pg_prepare($dbconn, "insert_accounts", 'INSERT INTO accounts (username, password, email, phone_number) VALUES ($1,$2,$3,$4)');
    $result = pg_execute($dbconn, "insert_accounts", $test); //this works
    $result = pg_execute($dbconn, "insert_accounts", $values); //the data table in PGAdmin skips a primary key every time this file runs; it is because of this line (see edit below).
    if (!$result) {
        echo "An INSERT query error occurred.\n";
        exit;
    }
    pg_close($dbconn);
?>

谢谢!

编辑 :以前没有显示,但是当我打开localhost / register-form-component.php时,它提供以下输出:

Array
Warning: pg_execute(): Query failed: ERROR: null value in column "username" violates not-null constraint DETAIL: Failing row contains (31, null, null, null, null). in /Library/WebServer/Documents/register-form-component.php on line 16
An INSERT query error occurred.

我假设这意味着$ _POST包含[null,null,null,null]。 当将event[0]更改为http.post()中的event时,也会出现此错误。

编辑2第一个输出是console.log(event),第二个是console.log(event [0])

编辑3这是提交表单后网络标签中显示的内容

编辑4在网络下的标题选项卡中,它显示了这一点。

事实证明,PHP之所以将$ _POST显示为包含空值的原因是因为它为空,因为我没有声明要包含的内容。 使用Mike Brant的答案中的方法,我在代码中添加了以下几行:

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$username = $request->username;
$password = $request->password;
$email = $request->email;
$phoneNumber = $request->phoneNumber;

而且有效! 感谢Jaime耐心地遵守我的所有问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM