首页 文章

无法将隐藏的输入值从Angular传递给PHP

提问于
浏览
0

我创建了一个表单,我希望用户可以选择他们想要的房间等等 . 如果我将其作为下拉列表或作为输入类型输入信息,则通过PHP通过电子邮件提交 .

但是,如果我将输入类型更改为“隐藏”,则该值将完全消失,我在控制台中看到的是:

<input _ngcontent-c4 name="room" type="hidden" value class="ng-untouched ng-pristine ng-valid">

然后,在网络中,没有任何东西出现作为“房间”的对象 . (注意:其他对象确实出现 . )

然后,如果我只是将样式更改为“display:none;”并输入value =“ChosenRoom”,电子邮件中没有发送任何内容 . 事实上,尽管在控制台中清楚地显示出来

<input _ngcontent-c4 name="room" style="display: none;" type="text" value="ChosenRoom" class="ng-untouched ng-pristine ng-valid">

该对象未显示在网络中 .

知道可能是什么问题吗?

CODE:

(我已将它发布在一个基本的Plunker中:http://embed.plnkr.co/uUhPrStdw4kDhaus2xfO/

这个有用, but the user has to type in the room name in the form

HTML(注意:我遗漏了表单的剩余代码,假设它在这种情况下不相关 . 如果您认为这会有所帮助,我也很乐意发布它 . )

<form (submit)="sendEmail(message)" #f="ngForm">
    <input type="text" name="room" [(ngModel)]="message.room" #room="ngModel">
    <button type="submit" [disabled]="f.invalid" *ngIf="!f.submitted">
</form>

HTML - 这个没有显示控制台中的值 .

<form (submit)="sendEmail(message)" #f="ngForm">
    <input type="hidden" name="room" [(ngModel)]="message.room" #room="ngModel" value="ThisRoom">
    <button type="submit" [disabled]="f.invalid" *ngIf="!f.submitted">
</form>

HTML - 这个显示控制台中的值,但不显示网络中的任何对象 .

<form (submit)="sendEmail(message)" #f="ngForm">
    <input type="text" style="display: none;" name="room" [(ngModel)]="message.room" #room="ngModel" value="ThisRoom">
    <button type="submit" [disabled]="f.invalid" *ngIf="!f.submitted">
</form>

Typescript: Contact.Service.TS

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { Resolve } from '@angular/router';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';

export interface IMessage {
  name?: string,
  email?: string,
  room?: string,
  daterange?: string,
  message?: string
}

@Injectable()
export class AppService {
  private emailUrl = '/assets/email.php';

  constructor(private http: Http) {

  }

  sendEmail(message: IMessage): Observable<IMessage> | any {
    return this.http.post(this.emailUrl, message)
      .map(response => {
        console.log('Sending email was successfull', response);
        return response;
      })
      .catch(error => {
        console.log('Sending email got error', error);
        return Observable.throw(error)
      })
  }
}

PHP

<?php

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

$errors = '';

if(empty($errors))
{

    $postdata = file_get_contents("php://input");
    $request = json_decode($postdata);


    $from_email = 'general@mywebsite.com';
    $message = $request->message;
    $from_name = $request->name;

    $to_email = "myemail@gmail.com";

    $contact = "<p><strong>Name:</strong> $from_name</p>
                <p><strong>Email:</strong> $request->email</p>
                <p><strong>Room:</strong> $request->room</p>
                <p><strong>Dates:</strong> $request->daterange</p>";
    $content = "<p><strong>Message:</strong><p>$message</p>";




    $website = 'My Currently Not but soon to be Functioning Website';
    $email_subject = "$website: Received a message from $from_name";

    $email_body = '<html><body>';
    $email_body .= "$contact $content";
    $email_body .= '</body></html>';

    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
    $headers .= "From: $from_email\n";
    $headers .= "Reply-To: $from_email";

    $result = mail($to_email,$email_subject,$email_body,$headers);

    $response_array['status'] = 'success';
    $response_array['from'] = $from_email;
    $response_array['result'] = $result;

    echo json_encode($response_array);

    header($response_array);
    return $from_email;
} else {
    $response_array['status'] = 'error';
    echo json_encode($response_array);
    header('Location: /error.html');
}
?>

我感谢任何帮助或想法 .

谢谢!

布拉德

2 回答

  • 0

    我找到了解决这个问题的方法 . 它完全避免了隐藏的字段,我仍然不确定它们是否是问题 .

    工作方案:

    contact.component.html - 在这里,我避免隐藏输入并传递消息旁边的文本 . 特别注意 'This particular room'

    <form (submit)="sendEmail(message, 'This particular room')" #f="ngForm">
    ...
    </form>
    

    contact.component.ts - 特别注意 message.room = room;

    import { Component, OnInit, HostBinding } from '@angular/core';
    import { AppService, IMessage } from '../../contact/contact.service';
    
    @Component({
      selector: 'app-contact',
      templateUrl: './contact.component.html',
      styleUrls: ['./contact.component.css']
    })
    export class TheensuiteComponent implements OnInit {
        message: IMessage = {};
    
      constructor(private appService: AppService) { }
    
      sendEmail(message: IMessage, room:string) {
        message.room = room;
        this.appService.sendEmail(message).subscribe(res => {
          console.log('ContactComponent Success', res);
        }, error => {
          console.log('ContactComponent Error', error);
        })
      }
    
      ngOnInit() {
        };
      }
    }
    

    其他一切都保持不变(contact.service.ts和email.php) .

    当然,这是一个轻微的黑客攻击 . 如果我想传递更多信息,这可能会很快导致混乱的代码 .

  • 1

    首先,没有添加该值,因为 ngModel 会覆盖 value ,因此与隐藏的事实无关 . 其次,我建议你可以在这里使用模型驱动的表格 . 有时一个模型驱动的形式是矫枉过正,但在这种情况下,我认为如果你想考虑它,我会为你提供这个选项 .

    您需要导入 ReactiveFormsModule 并将其添加到ngModule中的 imports 数组中 . 然后将以下内容导入组件并在构造函数中注入 FormBuilder

    import { FormBuilder, FormGroup, Validators } from '@angular/forms';
    
    constructor(private fb: FormBuilder) {}
    

    然后使用您想要的验证器构建表单:

    this.myForm = this.fb.group({
      room: ['theEnsuite'],
      name: ['', Validators.required],
      email: ['', [Validators.required, Validators.pattern('[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$']],
      message: ['', [Validators.required, Validators.minLength(10)]]
    })
    

    然后你可以摆脱双向绑定,并与表单控件交换它 . 好消息是,您根本不需要在模板中包含 room . 很好地已经坐在表单对象:)这是 name 输入的示例,其中包含错误消息:

    <input placeholder="Name" formControlName="name">
    <div *ngIf="!myForm.get('name').valid && myForm.get('name').touched">
      <p>Please enter your name.</p>
    </div>
    

    当您提交表单时,使用 myForm.value 作为参数 . 然后该对象与 IMessage 类型的对象相同,您可以直接使用此对象的post请求!

    这是上面的 DEMO .

相关问题