【问题标题】:Send POST request with JSON using Axios and CodeIgniter使用 Axios 和 CodeIgniter 发送带有 JSON 的 POST 请求
【发布时间】:2019-05-27 05:00:56
【问题描述】:

我正在尝试使用 Axios 发送数据:

axios.post( url,JSON.stringify({'i': '90'}))
    .then(function (response) {
        console.log(response);
    });

并在服务器上获取它:

var_dump(($this->input->post())); // Returns an array |  $_POST

对于上面的 JSON 值,我得到了这样的响应:

数组(2){ ["{"i":"90"}"]=> 字符串(0)“” [0]=> 字符串(0)“” }

没有JSON.stringifyvar_dump(($this->input->post()));$_POST 的结果是空数组。

如何使用 Axios 发送带有 JSON 数据的POST 请求并使用 PHP 在服务器上获取?

【问题讨论】:

  • 不是 100% 确定此解决方案是否也适用于 Axios,因此我不会将其标记为重复。但是this answer 可能会有所帮助。
  • 谢谢,让我检查一下。

标签: php ajax axios


【解决方案1】:

我也遇到了同样的问题,最后发现是因为XSS过滤, 使用

   $i = $this->input->post("i",false);

在 axios 中使用 so

var formdata=new FormData();
    formdata.append("key",value);

    this.axios.post("http://URL",formdata).then(res=>{})

【讨论】:

    【解决方案2】:

    这是一种可能的解决方案,但我认为必须有更好的方法。

    JS:

    axios.post( url,JSON.stringify({'i': '90'}))
    .then(function (response) {
        console.log(response);
    });
    

    PHP(CodeIgniter 动作):

        $requestData = json_decode(file_get_contents('php://input'), true);
    
        foreach ($requestData as $key => $val){
            $val = filter_var($val, FILTER_SANITIZE_STRING); // Remove all HTML tags from string
            $requestData[$key] = $val;
        }
        var_dump($requestData);
    

    回复:

    数组(1){ [“我”]=> 字符串(2)“90” }

    【讨论】:

      【解决方案3】:

      你需要使用json_decode:

      $json_data = json_decode($this->input->post());
      var_dump($json_data);
      
      echo $json_data->i;
      
      or
      
      foreach($json_data as $data){
         echo $data->i;
      }
      

      【讨论】:

        猜你喜欢
        • 2021-08-13
        • 1970-01-01
        • 2018-04-13
        • 2021-01-03
        • 1970-01-01
        • 2014-06-06
        • 1970-01-01
        相关资源
        最近更新 更多