代码之家  ›  专栏  ›  技术社区  ›  Jimmy

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

  •  -1
  • Jimmy  · 技术社区  · 7 年前

    应该发生什么:

    • 单击按钮时,它调用report.php并将“main”作为类型发送
    • 类型“main”在report.php中提取并用作$typename
    • $data varaible由main.json的内容填充

    >     [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
    

    索引.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>
    

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

    {
        "reportDescription":{ <....>
    }
    
    2 回复  |  直到 6 年前
        1
  •  4
  •   GrumpyCrouton    7 年前

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

    data: ({type: main}),

    data: {type: 'main'},
    

    (不需要多年生)

    将字符串发送到PHP文件。

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

    $typename = $_POST['type'];
    echo $typename;
    $data = file_get_contents("$typename.json");
    echo $data;
    
        2
  •  0
  •   David Lemon amitgoyal    7 年前

    data: {type: 'main'}, 作为 answered before .

    Server Side Request Forgery . 您需要在用户提供的数据和应用程序代码之间设置一个清晰的边界,您需要验证代码以避免对 file_get_contents :

    • 一个可以 请求随机网站 宋承宪

    • 有人可以 扫描你的目录

    所以,当心你用用户输入做什么,你需要验证它。我将使用以下代码。

      // 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; 
    
    推荐文章