gpt4 book ai didi

javascript - 这里的数组输出类型是什么

转载 作者:行者123 更新时间:2023-12-01 00:22:45 27 4
gpt4 key购买 nike

在第 24 行,我测试 test2[1] == "invalid" 是否永远不起作用,它总是转到 else 并带我到下一页。我认为 test2[1] 只是不是一个字符串,但我不知道它还会是什么,请帮忙

function login() {
var email = document.getElementById("email").value;
var passW = document.getElementById("password").value;

if (email == "" || passW == "") {
alert("Please enter a valid email or password.");
} else {
var myXMLRequest = new XMLHttpRequest();
myXMLRequest.onload = openWorkout;
var url = "assignment10.php?em=" + email + "&pass=" + passW;
myXMLRequest.open("POST", url, true);
myXMLRequest.send();
}
}

function openWorkout() {
var invalid = "invalid";
var step = this.responseText;
var test = step.split(",");
var test2 = test[0].split(":");
console.log(step);
console.log(test);
console.log(test2[1]);
if (test2[1] == "invalid") {
alert("The email or password you entered is invalid. Please try again.");
} else {
window.location = "#workoutPage";
}
}

<?php
//TASK 1: MAKE A CONNECTION TO THE DATABASE, DISPLAY ERROR FOR FAILED CONNECTIONS
//(FOR GODADDY) NOTE: $mysqli = new mysqli("127.0.0.1", "username", "password", "database", 3306);

$mysqli = new mysqli("localhost", "User", "1234", "ass10");
if ($mysqli->connect_errno) {
echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
//CHECK IF EMAIL AND ENTERED PASSWORD VALID (LOGIN PAGE [first part of open workout checks login password])
$entEmail = $_GET['em'];
$entPassword = $_GET['pass'];
$sql = "SELECT * FROM membership_table WHERE Email = $entEmail, Password = $entPassword";
$result = $mysqli->query($sql);
if($result->num_rows == 0) {
$data = "invalid";
} else {
$data = "valid";
}


//Pass to JSON
$json = array(
"data" => $data,
"Email" => $entEmail,
"Password" => $entPassword

);

header("Contenttype:Application/json");
print(json_encode($json));
?>

这是第 21 - 23 行的 console.log 输出

assignment10.js:21 {"data":"invalid","Email":"q","Password":"1"}
assignment10.js:22 (3) ["{"data":"invalid"", ""Email":"q"", ""Password":"1"}"]
assignment10.js:23 "invalid"

最佳答案

您正在从 PHP 返回 JSON,因此请使用 JSON.parse 对其进行处理。 ,而不是尝试将字符串分开:

var response = JSON.parse(this.responseText);
var test = response.data;
if (test == 'invalid') {
...

请注意,当前代码的问题是 test2[1]字面上 "invalid",包括双引号,因此对于您的测试要工作,您需要使用

if (test2[1] == '"invalid"') {

以下代码片段使用您的问题中的 console.log(step) 的输出来演示代码:

const responseText = '{"data":"invalid","Email":"q","Password":"1"}';
var response = JSON.parse(responseText);
var test = response.data;
if (test == 'invalid') {
console.log('Invalid!');
} else {
console.log('Valid!');
}

关于javascript - 这里的数组输出类型是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59276510/

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