[英]jQuery AJAX POST to PHP issue
I'm trying to evaluate the value of id
, which should be passed in the POST from jQuery to PHP. 我正在尝试评估id
的值,该值应在POST中从jQuery传递到PHP。
The call is returning {'id':'99'}
, which is ok if id
is not equal to 0. I wonder why ($x == "0")
is not being evaluated to true
in my PHP function. 调用返回{'id':'99'}
,如果id
不等于0是可以的。我想知道为什么($x == "0")
在我的PHP函数中没有被评估为true
。
Any help would be greatly appreciated! 任何帮助将不胜感激! Thanks in advance. 提前致谢。
jQuery: jQuery的:
$( document ).ready(function() {
$.ajax({
url: '/more.php',
type: 'POST',
data: JSON.stringify({"id" : "0"}),
success: function(data) {
$("body").append(data);
}
});
});
PHP: 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'}";}
I think it might be because PHP is converting the $_POST['id']
to integer. 我认为这可能是因为PHP将$_POST['id']
为整数。 Try the following: 请尝试以下操作:
function getmore($x) {
$x = intval( $x );
if ($x == 0) {
Another reason might be that your AJAX is sending the data incorrectly. 另一个原因可能是您的AJAX发送数据不正确。 Try using: 尝试使用:
data: {id : "0"}
in the AJAX request. 在AJAX请求中。
The data
setting in AJAX call accepts either PlainObject
or String
argument. AJAX调用中的data
设置接受PlainObject
或String
参数。 From the docs: 从文档:
It is converted to a query string, if not already a string. 如果还不是字符串,则将其转换为查询字符串。 It's appended to the url for GET-requests. 它被附加到GET请求的URL上。 See
processData
option to prevent this automatic processing. 请参阅processData
选项以防止这种自动处理。 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). 如果value是一个Array,则jQuery会根据传统设置(如下所述)的值,使用相同的键序列化多个值。
Why don't you use 你为什么不使用
$(document).ready( function() {
var id_main = 0;
$.ajax ({
type: "POST",
url: "/more.php",
data: { id: id_main },
});
});
send your data like this. 这样发送您的数据。 data: {"id" : "0"}, 数据:{“ id”:“ 0”},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.