[英]PHP isn't recognizing data posted by ajax
我正在向我的PHP腳本發送一個ajax調用,如下所示:
function load(){
var request = {};
request['action'] = 'load';
request['file'] = 'lorem_ipsum.txt';
$.ajax({
type: 'POST',
url: cgi_file,
data: JSON.stringify(request),
processData: false,
dataType: 'html',
contentType: 'application/html',
success:function(response){
console.log("received " + response);
}
});
}
我的PHP腳本如下:
$content_dir = '/static/content/';
$action = $_POST['action'];
switch ($action){
case 'load':
$file = $_POST['filename'];
echo file_get_contents($content_dir . $file);
exit();
}
PHP正在響應以下故障:
Notice: Undefined index: action in /var/www/river/api.php on line 5
這是什么問題?
只需按原樣保留data
:
data: request,
您不需要對其進行字符串化。
此外,您的file
參數允許攻擊者從您的文件系統中讀取任意文件。 消毒它。
嘗試溝渠processData: false
和contentType: 'application/html'
,它應該工作
$.ajax({
type: 'POST',
url: cgi_file,
data: request,
dataType: 'html',
success:function(response){
console.log("received " + response);
}
});
這里有一些問題,首先是contentType
屬性用於發送到服務器的數據,其次dataType應設置為text
因為這是您從服務器接收的內容。 如果你想在$_POST
數組中接收數據,你的javascript應該是這樣的,
$.ajax({
type: 'POST',
url: cgi_file,
data: {
action: "load",
file: "lorem_ipsum.txt";
},
dataType: 'text',
success:function(response){
console.log("received " + response);
}
});
Jquery會將您的數據作為標准帖子發送到服務器端代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.