将AJAX中的post变量发送到PHP文件中以获取变量

问题描述 投票:-1回答:2

会发生什么:

  • 单击按钮时,它会调用report.php并将“main”作为类型发送
  • 在report.php中选择“main”类型并将其用作$ typename
  • 使用main.json的内容填充$ data变量

会发生什么:

>     [25-Sep-2018 13:56:56] WARNING: [pool www] child 11 said into stderr: "NOTICE: PHP message: PHP Notice:  Undefined index: type in
> /var/www/html/report.php on line 27"
>     [25-Sep-2018 13:56:56] WARNING: [pool www] child 11 said into stderr: "NOTICE: PHP message: PHP Warning:  file_get_contents(.json):
> failed to open stream: No such file or directory in
> /var/www/html/report.php on line 28"
>     2018/09/25 13:57:00 [error] 8#8: *5 FastCGI sent in stderr: "PHP message: PHP Notice:  Undefined index: type in
> /var/www/html/report.php on line 27

的index.php

<script>
$(document).ready(function(){
    $("button").click(function(){
        $.ajax({
            url: 'report.php',
            type: "POST",
            dataType:'json',
            data: ({type: main}),
            success: function(result){
                $("#output").html(result);
            }
        }); 
    });
});
</script>

report.php

$typename = $_POST['type'];
echo $typename;
$data = file_get_contents("$typename.json");

main.json

{
    "reportDescription":{ <....>
}
javascript php
2个回答
4
投票

问题是你试图将未定义的变量main发送到你的php文件。此变量不存在,因此您收到错误。字符串必须用单引号或双引号括起来。

你应该将data: ({type: main}),改为

data: {type: 'main'},

(不需要括号)

将字符串发送到PHP文件。

现在在PHP文件中,您需要输出$data

$typename = $_POST['type'];
echo $typename;
$data = file_get_contents("$typename.json");
echo $data;

0
投票

你应该将data: {type: 'main'},改为answered before

但是答案中的php代码可以改进。此代码可能导致安全问题,特别是对Server Side Request Forgery。您需要在用户提供的数据和应用程序代码之间设置清晰的边界,您需要验证代码以避免使用file_get_contents的一些恶意:

  • 可以通过http请求随机网站或使用其他协议(如ssh)连接到可从Web服务器访问的其他服务器
  • 有人可以扫描您的目录并读取操作系统文件

因此,请注意您对用户输入所做的操作,您需要对其进行验证。我会使用以下代码。

  // strip all slashes and directories, use only the filename
  $typename = basename($_POST['type']);
  $filename = __DIR__.'/'.basename($_POST['type']).".json";

  if (!file_exist($filename)){
     echo "ERROR";
  }
  // do not output anything till validated
  // echo $typename;
  // use a header to tell the user that this is a json file
  header('Content-Type: application/json');
  $data = file_get_contents($filename);
  echo $data; 
© www.soinside.com 2019 - 2024. All rights reserved.