簡體   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