【问题标题】:JSON post method in phpphp中的JSON post方法
【发布时间】:2017-06-23 20:58:45
【问题描述】:

当我尝试从 angular 到 php 的 post 方法中获取我的值时,我不知道我做错了什么,似乎一切都是正确的,但是我无法看到邮递员的任何值/正确返回.

这是我所有尝试的 php 方法:

public function created()
{
    $json = file_get_contents('php://input');
    $json_string_in_array = array($json);
    $json_array =json_decode($json_string_in_array[0]);
    var_dump($json_string_in_array);
    var_dump($json_array);
    //return $json_array;
  //  $data = json_decode(file_get_contents('php://input'), true);
   // $data = json_encode(file_get_contents("php://input"));
  //  $request = json_decode($data);
  //  var_dump($data);
  //  return $data;
  //  return $request;
  //  $json = file_get_contents('php://input');
    //$obj = json_decode($json);
     // get the raw POST data
    // $rawData = file_get_contents("php://input");
    // this returns null if not valid json
    // return response()->json($rawData);
    //  DatabaseModel::DatabaseModel($json_array);
}

我要做的是获取该数据,然后将其发送到 DatabaseModel 以便将其添加到数据库中。

【问题讨论】:

  • 你的编码类型是什么?
  • application/x-www-form-urlencoded 这是我的 Angular 发布方法:function PostReview(JSONObject) { if(JSONObject!=null){ $http({ url: 'http://localhost:8000/creation', method: "POST", data: JSONObject, headers: { "Content-Type": "application/x-www-form-urlencoded;charset=utf-8;", "Accept": "application/json" } }); console.log(JSONObject); } }
  • $json = file_get_contents('php://input'); var_dump($json); 返回什么?
  • 在邮递员中我得到: string(0) "" 在浏览器中网络响应: string(80) "{"name":"test","surname":"testsurn","email": "ss@gmail.com","re​​view":"text text"}" 我想我明白了,它得到了正确的数据,我现在不知道如何正确访问它以在邮递员中看到,对吧?跨度>

标签: php angularjs json


【解决方案1】:

首先你的标题,content-type,应该是application/json。您是否手动将标题设置为角度?我很确定 Angular 会检测到(或者至少是默认的)内容类型,如果它没有设置,所以在你的情况下它会是 application/json

<?php
$json = file_get_contents('php://input');
$request = json_decode($json);
$name = $request->name;
$email = $request->email;
# etc
?>

【讨论】:

  • Angular:function PostReview(JSONObject) { if(JSONObject!=null){ $http({ url: 'http://localhost:8000/creation', method: "POST", data: JSONObject, headers: { "Content-Type": "application/x-www-form-urlencoded;charset=utf-8;", "Accept": "application/json" } }); } } 我得到这个尝试你的例子:( ` '试图获取非对象的属性', 'C:\\wamp64\\www\\GuestBook\\Book\\ lumen\\app\\Http\\Controllers\\DatabaseController.php', 30, array('json' => '', 'request' => null))`
  • 您的内容类型仍然设置不正确
  • XMLHttpRequest 无法加载 localhost:8000/creation。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'localhost' 不允许访问。然后我得到这个错误..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多