我正在尝试评估 id
的值,该值应在 POST 中从 jQuery 传递到 PHP。
调用返回 {'id':'99'}
,如果 id
不等于 0,这是可以的。我想知道为什么 ($ x == "0")
在我的 PHP 函数中没有被评估为 true
。
任何帮助将不胜感激!提前致谢。
jQuery:
$( document ).ready(function() {
$.ajax({
url: '/more.php',
type: 'POST',
data: JSON.stringify({"id" : "0"}),
success: function(data) {
$("body").append(data);
}
});
});
PHP:
if (isset($_POST['id'])) {
$con=mysqli_connect("localhost","user","pass","schema");
getmore($_POST['id']);
function getmore($x) {
if ($x == "0") {
$sqldata = mysqli_query($con,"SELECT * FROM IRCLOG WHERE DATETIME >= date_sub(curdate(),interval 1 day)");
}
else {
$sqldata = mysqli_query($con,"SELECT * FROM IRCLOG WHERE DATETIME >= date_sub(curdate(),interval 1 day)");
}
// your business logic
$rows = array();
while($r = mysqli_fetch_array($sqldata)) {
$rows[] = $r;
}
echo json_encode($rows);
}
}
else {echo "{'id':'99'}";}
最佳答案
我认为这可能是因为 PHP 正在将 $_POST['id']
转换为整数。请尝试以下操作:
function getmore($x) {
$x = intval( $x );
if ($x == 0) {
另一个原因可能是您的 AJAX 发送数据不正确。尝试使用:
data: {id : "0"}
在 AJAX 请求中。
AJAX 调用中的data
设置接受PlainObject
或String
参数。来自文档:
It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See
processData
option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
关于php - jQuery AJAX POST 到 PHP 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21844106/