我正在尝试通过 AJAX 将一组变量发送到 PHP 脚本。
通常情况下,我会这样做:
$('.submitSearch').on('click', function()
{
var rep = $('#rep').val();
var num = $('#num').val();
var uid = $('#uid').val();
// and so on
// then I could send each variable to a PHP script
$.post('api/summary.php', {rep: rep, num: num, // and so...}, function(data)
{
console.log(data);
});
});
我通常就是这样做的。
但是现在,我尝试在一个调用 searchCriteria 的变量中发送所有参数,如下所示:
$('.submitSearch').on('click', function()
{
var searchCriteria =
{
rep: $('#rep').val(),
num: $('#num').val(),
uid: $('#uid').val(),
// and so on...
}
// then send them to the php script
$.post('api/summary.php', searchCriteria, function(data)
{
console.log(data);
});
});
然后,在 PHP 脚本中,从变量中检索所有参数进行处理:
<?php
if($_POST['searchCriteria'] == true)
{
// get the parameters
// build the query
// return JSON
}
?>
我的问题是:如何从 PHP 脚本中的 $_POST['searchCriteria'] 获取所有参数?
最佳答案
尝试将其包装在一个更大的对象中,如下所示:
Javascript:
$('.submitSearch').on('click', function()
{
var searchCriteria =
{
rep: $('#rep').val(),
num: $('#num').val(),
uid: $('#uid').val(),
// and so on...
}
// then send them to the php script
$.post('api/summary.php', {searchCriteria : searchCriteria }, function(data)
{
console.log(data);
});
});
PHP:
<?php
if($_POST['searchCriteria'] == true)
{
$searchCriteria = json_decode($_POST['searchCriteria']);
// Now you can for each loop throught it for example
foreach($searchCriteria as $key => $value) {
// Do something
}
}
?>
关于javascript - jQuery AJAX 发送搜索条件到 PHP 返回 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40685985/