【问题标题】:Aurelia PHP Post request empty $_POSTAurelia PHP Post 请求为空 $_POST
【发布时间】:2016-10-07 10:45:46
【问题描述】:

我在向服务器发出 POST 请求时遇到问题,我的数据没有发回给我。

我有一个非常简单的 PHP 脚本:

服务器脚本

<?php
   header('Access-Control-Allow-Origin: *');
   header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

   echo json_encode("{user-id:" . $_POST["user_id"] . "}");
 ?> 

我想向该脚本发出 POST 请求,并获取一些 JSON 数据作为响应。


工作要求

如果我从 HTML 发出 POST 请求,这将完美运行:

<form method="post" action="http://url/post.php">
  <input type="hidden" name="user_id" value="123" />
  <button>Go to user 123</button>
</form>

这也有效:

$.post( "url/post.php", this.data)
  .done(function( data ) {
    console.log( data );
  });

回应

"{user-id:123}"

 


不工作的脚本(欲望):Aurelia Fetch Client (JS2016)

submit(){
    let comment = { user_id: "234" };
    this.http.fetch('post.php', {
      method: 'post',
      body: json(comment)
    })
      .then(response => response.json())
      .then(data => console.log(data));
}

获取客户端配置

config
  .useStandardConfiguration()
  .withBaseUrl('url')
  .withDefaults({
    mode: 'cors',
    headers: {
      'Accept': 'application/json'
    }
  });
});

回应

{user-id:}

php 替代方案

我尝试在 PHP 中查看数组中的内容,但使用 implode 得到了相同的结果:

echo json_encode("{user-id:" . (string)implode(" ",$_POST) . "}");

问题

Aurelia 似乎没有以正确的方式发布数据。我在这里犯了错误,还是我不知道的一些配置设置?

【问题讨论】:

  • json 函数是什么?请注意,您的原始表单确实发布了 application/x-www-form-urlencoded 正文,而不是 json。而且你编码 JSON 的 PHP 例程很糟糕——如果你想要一个 JSON 对象,你不应该将字符串传递给json_encode
  • 你能不能把body: json(comment)改成body: JSON.stringify(comment)看看会发生什么?
  • @Bergi json 函数是 Aurelia 的建议之一。删除它并传递有效的 JSON 并没有解决问题,字符串也没有。至于PHP;我不是 PHP 程序员,但我想看看我的 POST 是否以正确的方式被解雇。 PHP 确实返回了 JSON,每当我返回一个正常的字符串或其他东西时,http-fetch-client 就会出错。
  • PHP 应该返回的 JSON 格式如下:{"user-id":"123"}
  • @Bergi 如果我将http-fetch-client 更改为$.post() 它确实有效,这是否意味着PHP 没问题?我确实将其更改为:echo json_encode($_POST);$_POST 数组转换为 json。

标签: javascript php json ecmascript-6 aurelia


【解决方案1】:

而不是“_POST[“user_I'd”]”这样做

$input = file_get_contents('php://input');
$input = json_decode($input);
//access user_id like this:
$input->{'user_id'}

【讨论】:

  • 对于评论也做:JSON.stringify(comment)
  • 有人在这里遇到了类似的问题stackoverflow.com/questions/1282909/…
  • Tnx 为那个@Mark。在手机的小屏幕上打字
  • 想知道$input-&gt;{'user_id'}我还以为是$input-&gt;user_id
  • 我已经看到两者都可以工作。我的不带引号的版本似乎也可以使用
猜你喜欢
  • 2020-02-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-27
相关资源
最近更新 更多