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

标签 php javascript json casting

我正在使用 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

最佳答案

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

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

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

关于php - PHP 会自动将数字转换为字符串吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7967878/

相关文章:

javascript - 强参数要求

java - 如何在 Java 中将类显示为 JSON 响应?

php - 将 JSON 数据从 Javascript 发送到 PHP?

c# - 使用 C# 将 csv 文件转换为 json

php - 如何在 PHP 中将日期转换为时间戳?

php - mysql 查询只返回在特定时间后添加的行

javascript - 验证表单 JavaScript

javascript - Canvas 中的弹跳球

php - 连续显示3张图片的问题

php - 在 laravel 默认通知表中为 "type"列添加自定义值