PHP自动将数字转换为字符串吗?

3
我将使用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

@Blender -- 所有密码信息仍然在历史记录中 ^_^ - Naftali
1
你可以用 $result['valid'] = $emailQuerry; 来替换整个代码块:if ($emailQuerry) {... } - Blender
这只是本地凭据而已。真的那么重要吗? - Michael Myers
1
那其实不是我的密码…只是我试图卖个笑而已。 - puk
@Blender 我对PHP非常非常新。我会感激高级教程的链接。几乎所有的PHP教程都讲解最基本的主题,如for循环,变量,字符串,GET,POST……但还是谢谢你的提示。 - puk
显示剩余12条评论
3个回答

3

json_encode 把所有变量都编码成字符串。

因此,JavaScript 将其视为字符串。

因此,在 JavaScript 中您可以使用 parseInt(...)


JSON是执行我正在进行的操作的最佳/首选/可接受方式吗?我宁愿从一开始就正确地做事。谢谢。 - puk
@puk 这是我首选的方式(如果这对你来说足够了 ^_^) - Naftali
2
json_encode 不会将所有的值都编码为字符串。数字、true、false 和 null 都可以使用 json_encode 正确地编码。实际原因是所有标量 $_GET 参数都是字符串,所以应该在那里将其转换为数字:$result['time'] = (float)$_GET["time"]; - Thai
@Thai,我只需要在客户端进行转换。 - puk
@Neal,我喜欢你的回答,但是由于你的一些陈述不准确,我正在受到相当大的压力选择它。你能否提及JSON_NUMERIC_CHECK并将“必须使用”更改为“可以使用”? - puk

2

这是一个很好的知识,但是 GET 总是返回一个字符串,所以这种方法在这里不适用。 - puk

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]

你的答案也是正确的,但我会选择Neal的答案,因为我认为在客户端进行这些计算更容易。如果有人认为必须在服务器端完成此操作,我将考虑将正确答案改回muu。 - puk
@puk:尼尔的方法是有效的,但他错了,这并不是唯一的方法。 - user542603

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接