所以我有一個問題,即使用php編碼的數據在javascript中沒有正確解碼。這裏是錯誤: ErrorPHP json編碼在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));
}
?>
也許你有空間發生某處或某些不可見的字符,可能在頁面頂部的<?php'之前? – Rasclatt
在嘗試JSON.parse()之前requestObject看起來像什麼? – tpdietz
以下是它的樣子:{「returnValue」:「account_in_use」} – steve