[英]PHP json encode not properly decoding in javascript
所以我有一個問題,其中使用php編碼的數據無法在javascript中正確解碼。 這是錯誤: 錯誤
JSON看起來不錯,但是javascript拋出錯誤,我不知道為什么。
這是我的代碼:
JS:
function requestData( url )
{
document.getElementById( "spinner" ).style.visibility = "visible";
var xhttp;
xhttp = new XMLHttpRequest( );
xhttp.onreadystatechange = function( ) {
if ( this.readyState == 4 ) {
if( this.status == 200 )
{
document.getElementById( "spinner" ).style.visibility = "hidden";
console.log( this.responseText );
return this.responseText;
}
else
{
document.getElementById( "spinner" ).style.visibility = "hidden";
document.getElementById( "errorsec" ).innerHTML = ":( An unknown error has happened and your request was canceled. Code: " + this.status;
return false;
}
}
};
xhttp.open( "GET", url, true );
xhttp.send( );
}
function handleSignup( )
{
var username = document.getElementById( "un" ).value; // Get text field values
var password = document.getElementById( "pw" ).value;
var requestObject = requestData( "../../FRAMEWORK/createaccount.php?name=" + username + "&password=" + password, false );
var returnObject;
if( requestObject != false )
{
requestObject = JSON.parse( requestObject );
console.log( returnObject.value );
}
}
PHP:
<?php
# REV 1.0.0
$name = $_GET[ "name" ]; # Get values to set
$password = $_GET[ "password" ];
$file = fopen( "../USER_STORE/userindex.json", "r" ); # Load user index
$accounts = json_decode( fread($file, filesize( "../USER_STORE/userindex.json" ) ), true );
fclose($file);
$alreadyExists = false; # Check to see if username already is in use
foreach($accounts as $val) {
if( $val == $name )
{
$alreadyExists = true;
}
}
if( !$alreadyExists ) # If username is not in use
{
$UUID = sizeof( $accounts ) + 1;
$toAppend = array( "username" => $name, "password" => hash( "sha256", $password ) ); # Create append list
mkdir( "../USER_STORE/" . $UUID ); # Append user data
$file = fopen( "../USER_STORE/" . $UUID . "/accountinfo.json", "w" );
fwrite( $file, json_encode( $toAppend ) );
fclose( $file );
$accounts[ $UUID ] = $name; # Create new user index
$file = fopen( "../USER_STORE/userindex.json", "w" ); # Update userindex
fwrite( $file, json_encode( $accounts ) );
fclose( $file );
$return = array( "value" => "created" ); # Return message
echo( json_encode( $return ) );
}
else # Account is in use
{
$return = array( "value" => "account_in_use" ); # Return error message
echo( json_encode( $return ) );
}
?>
XMLHttpRequest
異步工作。 因此,您的功能requestData
在xhttp.send();
之后結束xhttp.send();
並且不返回任何東西。 readystatechange
的事件處理程序(稍后,一旦XMLHttpRequest
實際上接收到來自服務器的響應,將調用該事件處理程序)確實返回了一個值,但是對此沒有做任何事情。
解決方案:在該事件處理程序中移動響應的解析和解釋。
補充筆記:
構建URL時,需要轉義參數(使用encodeURIComponent
)。 如果兩個字段中的任何一個包含空格或特殊字符(例如%
或&
,您會怎么辦?
哈希密碼時,必須先對其加鹽。 或使用現成的函數(例如password_hash
將為您完成此操作。
您可能要使用file_get_contents
/ file_put_contents
來讀取/寫入您的用戶文件,這將大大簡化您的代碼。 或更好的是,數據庫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.