【问题标题】:Http.post form data from angular2+ to php从 angular2+ 到 php 的 Http.post 表单数据
【发布时间】:2017-12-21 21:39:30
【问题描述】:

我已经花了好几个小时来寻找这个,但我找不到任何人试图做我曾经做过的事情。 我正在尝试使用 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();
  }

}

注册表单组件.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]。 当 http.post() 中的 event[0] 更改为 event 时,也会出现同样的错误。

编辑 2First output is of console.log(event), second is of console.log(event[0])

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

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

【问题讨论】:

  • $_POST 的内容是什么?
  • 如何检查? @Jaime
  • error_log(print_r($_POST, true)); 然后查看错误日志
  • 我已经编辑了帖子以显示 $_POST 中的内容
  • 好的。 console.log(event[0]) 输出什么?

标签: php angular forms http-post


【解决方案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 耐心地回答我的所有问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-07
    • 1970-01-01
    • 2016-04-18
    • 1970-01-01
    相关资源
    最近更新 更多