【问题标题】:Does PHP automatically convert numbers to strings?PHP会自动将数字转换为字符串吗?
【发布时间】:2011-11-01 14:20:38
【问题描述】:

我正在使用 dojo 和 ajax 向 PHP 发送时间戳,PHP 会检查数据库,然后返回时间戳以进行调试。当我发送这个时间戳时,它是一个数字,当它返回时,它是一个字符串。这有什么具体原因吗?我应该怎么做才能避免这种情况(在 PHP 中转换为 int,通过 JSON 修复,或在 javascript 中转换为 int)

这里是道场代码

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 -- 所有密码信息仍在历史记录中^_^
  • 您可以将整个块:if ($emailQuerry) {... } 替换为 $result['valid'] = $emailQuerry;
  • @Neal,在历史上比在公开场合更好。感谢您告诉 erryone ;)
  • @Blender 大声笑我把它标记为一个模组。
  • 这实际上不是我的密码...这是我的幽默尝试。

标签: php javascript json casting


【解决方案1】:

json_encode 将所有变量编码为字符串。

因此 javascript 会将其视为字符串。

所以在javascript中你可以使用parseInt(...)

【讨论】:

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

您可以使用json_encode() 通过JSON_NUMERIC_CHECK 选项从PHP(后编码)输出您的数字。

【讨论】:

  • 这很好,但是,GET 总是返回一个字符串,所以这种方法在这里不适用。
【解决方案3】:

将整数作为整数发送很简单 - 为 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 的 b/c 我认为在客户端进行这些计算更容易。如果有人认为这必须在服务器端完成,我会考虑将正确答案改回 muu。
  • @puk:尼尔的方法是有效的,但他错了,这是唯一的方法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-04
  • 2013-05-12
  • 1970-01-01
  • 2014-09-05
相关资源
最近更新 更多