我正在使用dojo和ajax向PHP发送时间戳,它会进行数据库检查,然后返回时间戳以进行调试。当我发送这个时间戳时,它是一个数字,当它返回时,它是一个字符串。这有什么特别的原因吗?我该怎么做才能避免这种情况(在PHP中转换为int,通过JSON修复或在javascript中转换为int)
这是Dojo代码
dojo.xhrGet({
url: 'database/validateEmail.php',
handleAs: "json",
content: {
email : 'George.Hearst@Pinkerton.dw',
time: 0
},
load: function(args) {/*SEE BELOW*/}
});
这是PHP脚本
<?php
/**
** connect to the MySQL database and store the return value in $con
*
*/
$con = mysql_pconnect("localhost:port", "username", "password");
/**
** handle exceptions if we could not connect to the database
*
*/
if (!$con) {
die('Could not connect: ' . mysql_error());
}
/**
** Create table query
*
*/
mysql_select_db("portal", $con);
/**
** Get user entered e-mail
*
*/
$emailQuerry = mysql_num_rows(mysql_query("SELECT EMAIL FROM user WHERE EMAIL='" . $_GET["email"] . "'")) == 1;
/**
** Whether successful or not, we will be returning the time stampe (this is used to determine whether there were any changes between the time a request
** was sent, and when this response was returned.
*
*/
$result['time'] = $_GET["time"];
/**
** Currently only checks to see if the two values were provided. Later, will have to check against passwords
*
*/
if ($emailQuerry) {
$result['valid'] = true;
}
else {
$result['valid'] = false;
}
echo json_encode($result);
?>
最后,加载功能在
之上留空了load: function(args) {
console.log(localArgs.time + ' v ' + args.time);
console.log(localArgs.time === args.time);
console.log(localArgs.time == args.time);
}
其输出为
0 v 0
false
true
答案 0 :(得分:3)
json_encode
将所有变量编码为字符串。
因此javascript会将其视为字符串。
所以在javascript中你可以使用parseInt(...)
答案 1 :(得分:3)
您可以使用json_encode()通过JSON_NUMERIC_CHECK选项从PHP(后编码)输出您的数字。
答案 2 :(得分:1)
以整数形式发送整数很简单 - 为json_encode提供一个! 把'(int)'放在你要转换的任何东西周围。
以下是一个例子:
echo json_encode(array(1, 2, 3));
输出:
[1,2,3]
另一个:
$a = '123';
echo json_encode(array($a, (int) $a));
输出:
["123",123]