如何使用Http.post(Angular 2)发布JSON对象(PHP服务器端) [英] How to post json object with Http.post (Angular 2) (php server side)

查看:142
本文介绍了如何使用Http.post(Angular 2)发布JSON对象(PHP服务器端)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试重新创建将JSON从angular 2发布到php ,但它不起作用,因为php端的$_REQUEST变量中没有任何内容

I'm trying to recreate Post JSON from angular 2 to php but it doesn't work as there's nothing in the $_REQUEST variable on php side

代码:

searchHttp({body}: any): Promise<any>
{   
    let headers = new Headers ({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers, method: "post" });

    let test_this = {"search": "person"};

    return this.http.post(this.post_url, JSON.stringify(test_this), options)
        .toPromise()
        .then(response =>  
            {   
                return response.text();
            })  
        .catch(this.handleError);
}

有什么我想念的吗?我知道帖子可以使用其他格式,因为我已经在另一个问题中回答了这个问题.

Is there something I'm missing? I know that posts works with another format because I have that answered in another question.

还有,http.requesthttp.post好吗?

在与Angular/Javascript专家进行了大量协商之后,他们认为这是一个php问题.因此,任何了解如何在php端接受JSON对象的人都将受到欢迎.

After much consultation with Angular/Javascript experts, they believe this is a php issue. So anyone with knowledge of how to accept JSON objects on php side will be gladly welcomed.

推荐答案

角度2客户端部分

 ngOnInit() { 

        let body=Api+'product.php'+'?id=' + this.link_id;
        this._callservice.callregister(body)
                    .subscribe( data => {
                                this.outputs=data;                           
                       }, 
                    error => console.log("Error HTTP Post"),
                    () => console.log("completed") );  
      }    
    }

call.service.ts

import {Injectable} from '@angular/core';
import {Router} from '@angular/router';
import {Http, Response, Headers, RequestOptions} from '@angular/http';
import {Observable}     from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

@Injectable()
export class AuthenticationService {

  constructor(private _http:Http){}

  postregister(api:any){
//      console.log(api);
  let headers = new Headers({'Content-Type':'application/x-www-form-urlencoded'});
  let options = new RequestOptions({ headers: headers, method: "post"});
      return this._http.get(api,options)
          .map(res => res.json())
          .catch(this.handleError);
  }
  private handleError (error: Response) {
        console.error(error);
        return Observable.throw(error.json().error || ' error');
    }

}

服务器端PHP 确保在服务器端,您在PHP代码中具有这三行内容.

Server side PHP make sure on server side you have these three lines in php code.

   header('Access-Control-Allow-Origin: *');    
    header('Access-Control-Allow-Headers: X-Requested-With');
    header('Access-Control-Allow-Methods: POST, GET, OPTIONS');

Php文件:

  <?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: X-Requested-With');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
$servername = "localhost";
$username1 = "root";
$password = "root";
$dbname = "product";

$e=array("error"=>1,"message"=>"Account Already Exists");

$accountCreated = array( "error" =>0, 
                         "data" => array(
                                   "username" => "amit" , 
                                   "password" => "anypassword",
                                   "role"=> "user", 
                                   "id" => "anyid" ) );

// Create connection
$conn = mysqli_connect($servername, $username1, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

    $username = $_GET["username"];
    $Pass = $_GET["password"];
    $role= $_GET["role"];
    $sql="SELECT COUNT(*) as user FROM users WHERE username = '$username'";
    $result = mysqli_query($conn,$sql);
    $line = mysqli_fetch_assoc($result);
    $count = $line['user'];
    if($count!=0)
       {
          echo json_encode($e);
       }
    else
       {
         $sql="INSERT INTO users(username,password,role)VALUES('$username','$Pass','$role')";
         $result=mysqli_query($conn,$sql);
         $sql="select * from users where username ='$username'";
         $result=mysqli_query($conn,$sql);
         $line=mysqli_fetch_assoc($result);
         {
             $accountCreated['data']['username']=$line['username'];
             $accountCreated['data']['password']=$line['password'];
             $accountCreated['data']['role']=$line['role'];
             $accountCreated['data']['id']=$line['id'];
         }
         echo json_encode($accountCreated);
        }

 ?>

我希望这对您有用..对于json,我想您应该将其作为选项传递,并对要在选项中使用的值使用json解码.

i hope this will work for you .. for json i guess you should pass as options and use json decode for values you get in options.

这篇关于如何使用Http.post(Angular 2)发布JSON对象(PHP服务器端)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆