由于AJAX,$ _POST为空

时间:2018-03-28 18:57:59

标签: javascript php jquery

问题: var_dump($ _ POST [' day']) NULL ,var_dump($ b) ;是字符串(0)"" 结果 - 返回空json

带有复选框的HTML表单

<form id="filter">
   <input type="checkbox" name="day[]" value="1"> 
   <input type="checkbox" name="day[]" value="2">
   <input type="checkbox" name="day[]" value="3"> 
</form>

JS

var a = 0;
var b = 5;
var c = $( "#filter" ).serialize();
var Data = 'a=' + a + '&' + 'b=' + b + '&' + c;
var process = false;
$.ajax({
    url: 'script.php',
    method: 'POST',
    data: Data,
    beforeSend: function() {
        process = true;
    }
});

script.php var_dump($ _ POST [&#39; day&#39;])为NULL

$a = $_POST['a'];
$b = $_POST['b'];
$c = implode(',', $_POST['day']); // Warning: implode(): Invalid arguments passed
$in  = str_repeat('?,', count($c) - 1) . '?'; // Warning: Second argument has to be greater than or equal to 0
$sql = "SELECT * FROM table WHERE day IN ($in) ASC LIMIT :a, :b";
$stmt = $pdo->prepare($sql);
$stmt->execute($с, [$a, $b]);
$data = $stmt->fetchAll();
echo json_encode($data);

1 个答案:

答案 0 :(得分:0)

$result = [];

$a = (int) $_POST['a'];
$b = (int) $_POST['b'];

$c = array_filter( (array) $_POST['day'] );

if ( !empty($c) )
{
 $c = implode(',', $_POST['day']);
 $c = explode(",", $c);
 $in = str_repeat("?,", count($c) - 1) . '?';
 $sql = "SELECT * FROM table WHERE day IN ($in) LIMIT ?, ?";
 $stmt = $pdo->prepare($sql);
 $params = array_merge($c, [$a, $b]);
 $stmt->execute($params);
 $data = $stmt->fetchAll();
 $result = $data;
}

echo json_encode($result);