Http.post从angular2 +到php形成数据

问题描述 投票:0回答:1

我花了几个小时搜索SO,但我找不到任何试图做我的事情的人。我正在尝试使用http.post从HTML表单通过Angular向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","[email protected]",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:First output is of console.log(event), second is of console.log(event[0])

编辑3:This is what shows up in the network tag after submitting the form

编辑4:In the header tab under network, it shows this.

php angular html-form-post
1个回答
1
投票

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

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

它奏效了!感谢Jaime耐心地遵守我的所有问题。

© www.soinside.com 2019 - 2024. All rights reserved.