duanqiao1926 2017-01-18 11:10
浏览 119
已采纳

在客观的ajax请求之后,filter_input与$ _POST上的直接访问之间的区别

I have different results by using filter_input(INPUT_POST, 'attribute') and $_POST['attribute'] and don't know why this happens.

The Post-Request is send by a JavaScript build with JQuery and looks like that:

// type javaScript
var formData = {
  field_a: "valueA",
  field_b: "",
  field_c: undefined
};
$.ajax({
  url: 'serverAddress',
  data: {action: 99, formData: formData},
  dataType: 'json',
  method: 'post',
  success: function(){
    console.log(arguments)
  }
});

My PHP-Script looks like that:

// type php
$requestMethod = INPUT_POST;
$response = [
  "fi-result" => filter_input($requestMethod, 'formData'),
  "direct-result" => $_POST['formData'];
];
echo json_encode($response);

the result what is coming back is not what i was awaiting because the access via filter_input returns falsein my tests and not an json object like the direct access on the super global $_POST.

// type json response
{
  "fi_result": false,
  "direct-result": {
    "field_a": "valueA",
    "field_b": ""
  }
}

Why are there differences between using filter_input and direct access on $_POST?

I don't want to access the super global $_POST. Is there any way to use filter_input like above without encode formData to a String in JavaScript and decode it in PHP one simple step after encoding?

By the way. I'm using TypeScript to generate my JavaScript. That is not supporting the FormData Object (transpiler throws error on new FormData()). So i can't use this.

  • 写回答

1条回答 默认 最新

  • douzhong6480 2017-02-19 17:10
    关注

    I found the answer deep in the PHP docs. POST is not build to transport deep object. And filter_input method tries to get simple datatypes like string or int. this method does not parse internal so i have to send it as JSON string and decode it or i can't use filter_input in my case.

    i took the first and send now strings.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?