会发生什么:
会发生什么:
> [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":{ <....>
}
问题是你试图将未定义的变量main
发送到你的php文件。此变量不存在,因此您收到错误。字符串必须用单引号或双引号括起来。
你应该将data: ({type: main}),
改为
data: {type: 'main'},
(不需要括号)
将字符串发送到PHP文件。
现在在PHP文件中,您需要输出$data
。
$typename = $_POST['type'];
echo $typename;
$data = file_get_contents("$typename.json");
echo $data;
你应该将data: {type: 'main'},
改为answered before。
但是答案中的php代码可以改进。此代码可能导致安全问题,特别是对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;