簡體   English   中英

PHP會自動將數字轉換為字符串嗎?

[英]Does PHP automatically convert numbers to strings?

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

json_encode將所有變量編碼為字符串。

所以javascript會把它看作一個字符串。

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

您可以使用json_encode()從PHP(后編碼)輸出您的數字,使用JSON_NUMERIC_CHECK選項。

要以整數形式發送整數很簡單 - 為json_encode提供一個! 把'(int)'放在你想要轉換的任何東西周圍。

這是一個例子:

echo json_encode(array(1, 2, 3));

輸出:

[1,2,3]


而另一個:

$a = '123';
echo json_encode(array($a, (int) $a));

輸出:

["123",123]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM