我将从mySQL表读取的简单关联数组回显给jQuery b.m.o json_encode($ array)方法。但是,我的.ajax调用在jquery中失败,这似乎是由于该对象不是有效的json对象。我在chrome中进行了一些调试,并在“网络”标签下验证了响应预览-确实看起来是完美的json格式:
{“ UserName”:“ DehanL”,“ UserPassword”:“ admin”,“ UserEmail”:“ [email protected]”}
这是我的PHP:
<html>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbName ="dbPodiumPro";
$inUsername = $_POST["name"];
$inPassword = $_POST["password"];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbName);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Use the dbPodiumPro
mysqli_select_db($conn,"dbPodiumPro");
$sql = "SELECT * FROM users WHERE UserName='$inUsername' AND UserPassword ='$inPassword' ";
$result = mysqli_query($conn,$sql);
// Fetch one row
$row=mysqli_fetch_assoc($result);
//Check to see if the username and password combo exists
if(!empty($row['UserName']) AND !empty($row['UserPassword']))
{
//$_SESSION['UserName'] = $row['UserPassword'];
//echo $_SESSION;
echo json_encode($row);
}
else { echo "Be gone imposter!"; }
$conn->close();
?>
</body>
</html>
然后是jQuery:
$.ajax({
type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
url: 'php/loginrequest.php', // the url where we want to POST
data: formData, // our data object
dataType: 'json' // what type of data do we expect back from the server
})
// using the done promise callback
.done(function (data) {
console.log("ajax done callback");
})
.fail(function (data) {
console.log(data, "ajax failed callback");
var IS_JSON = true;
try {
var json = $.parseJSON(data);
} catch (err) {
IS_JSON = false;
}
console.log(IS_JSON);
});
最佳答案
您的PHP像这样开始:
<html>
<body>
此后无论输出什么,它都不会是有效的JSON。
我在chrome中进行了一些调试,并在“网络”标签下验证了响应预览
查看原始预览。您似乎正在查看渲染的HTML预览。
关于javascript - 使用json_encode()从PHP返回的Json对象,但是我的JavaScript中无效的json对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30096112/