gpt4 book ai didi

php - JSON 意外的 token

转载 作者:行者123 更新时间:2023-11-29 03:23:38 25 4
gpt4 key购买 nike

JSON.parse() 似乎不适用于我的代码,我不确定是什么原因造成的。

JS代码:

var obj = JSON.parse(this.responseText);
console.log(obj.status + " " + obj.type);
if (obj.status == "success") {
document.cookie = "accounttype=" + obj.type;
document.cookie = "name=" + obj.name;
var accounttype = getCookie(accounttype);
if (accounttype == "Seller") {
window.location.href = "../html/sell.html";
}
}

PHP 代码:

$count = mysqli_num_rows($result);
if($count == 1){
echo '{"status": "success", "type":"$account", "name":"$name"}';
}else{
echo '{"status": "failed"}';
}

希望大家帮帮我,谢谢!

编辑更新的代码

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var str = JSON.stringify(this.responseText);
var obj = JSON.parse(str);
console.log(obj.status + " " + obj.type);
if (obj.status == "success") {
document.cookie = "accounttype=" + obj.type;
document.cookie = "name=" + obj.name;
var accounttype = getCookie(accounttype);
if (accounttype == "Seller") {
window.location.href = "../html/sell.html";
}
} else {
sweetAlert("Oops...", "Invalid username or password!", "error");
document.getElementById("password").value = "";
}
}
}
xmlhttp.open("POST", "../php/login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("username=" + username + "&" + "password=" + password);

这是更新后的 PHP 代码:

<?php
include("checkdbconnection.php");

session_start();


$username = mysqli_escape_string($conn, $_POST['username']);
$password = mysqli_escape_string($conn, $_POST['password']);
$password = md5($password);

$getLogin = "SELECT * FROM user WHERE username = '$username' and password = '$password'";
$result = mysqli_query($conn, $getLogin);

$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
$name = $row["firstname"];
$account = $row["account_type"];

if(!$result){
echo "Query Error: ". mysqli_error($conn);
die();
}

$jsonsuccess = ["status": "success", "type": $account, "name": $name];
$jsonfail = ["status": "failed"];
$jsonsuccstring = json_encode($jsonsuccess);
$jsonfailstring = json_encode($jsonfail)
$count = mysqli_num_rows($result);
if($count == 1){
echo $jsonsuccstring;
}else{
echo $jsonfailstring;
}
?>

对于两个 JSON 返回值,控制台都返回未定义。

最佳答案

使用json_encode()

你的服务器端响应应该是

 $json = ["status": "success", "type": $account, "name": $name];

$jsonstring = json_encode($json);
echo $jsonstring;
die();

你的 JS 代码应该是这样的

$.ajax({  
type: "GET",
url: "URL.php",
data: data,
success: function(data){
// Here is the tip
var data = $.parseJSON(data);
//Here is success
alert(data.status);
}
});

编辑

您应该验证您的 json 字符串。如果没问题试试这个:

var jsonStr="your json string";
var json=JSON.stringify(jsonStr);
json=JSON.parse(json)

关于php - JSON 意外的 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39940764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com