【发布时间】:2018-01-23 00:07:43
【问题描述】:
我在从 PHP 接收 JSON 对象时遇到问题。我可以提醒它并使用dataType: 'text' 获得一个(我认为是正确的)JSON 对象,但不要像data.message 那样使用它——>它是“未定义的”。使用 dataType: 'json','jsonp' 或 ajax 调用 $.getJSON 它不起作用(它不会触发此请求)。
AJAX
$('#login').click(function () {
var name = $('#username').val();
var pass = $('#password').val();
$.ajax({
url: "http://localhost/weltenbummler/Weltenbummler1/Weltenbummler1/app/login.php?username=" + name + "&password=" + pass,
dataType: 'text',
type: 'GET',
success: function (d) {
alert(d);
alert(d.message);
}
});});
警报 JSON
{"status":"f","message":"Benutzername und Passwort stimmen nicht ueberein"} 或
{"status":"t","message":"Erfolgreich eingeloggt!","data":{"id":"1","mail":"abc","password":"123"}}
我在 jsonlint.com 上测试了收到的字符串,它应该是有效的。我试过 JSON.parse(data) , $.parseJSON(data) 什么不起作用。
JSON.stringify(data) 正在返回带有斜杠的 JSON(我不知道为什么)。
Postman 也能以 HTML、文本、XML 或 JSON 格式读取它...
在 php 中,我尝试将标题更改为
header("Content-type: application/json; charset=utf-8");
或强制响应为 JSON。
connect.php 文件:
<?php
$host = "127.0.0.1";
$user= "root";
$pw="";
$db = "weltenbummler";
//Create connection
$con = new mysqli($host,$user,$pw,$db);
//Check connection
if($con->connect_error){
die("Connection failed: " .$con->connect_error);
}?>
login.php 文件:
<?php
header('Content-type: application/json');
require 'connect.php';
$username = $_GET['username'];
$password = $_GET['password'];
$response = array();
if(empty($username)){
$response = array(
"status " => " f",
"message " => " Gebe einen Benutzernamen ein!"
);
die(json_encode($response));
}
if(empty($password)){
$response = array(
"status" => "f",
"message"=> "Gebe ein Passwort ein!"
);
die(json_encode($response));
}
$sqlstatement= ("SELECT id,mail,password FROM user WHERE mail = '$username' AND password = '$password'");
$result = mysqli_fetch_assoc($con->query($sqlstatement));
if (!$result) {
$response = array(
"status" => "f",
"message" => "Benutzername und Passwort stimmen nicht ueberein"
);
} else {
$response = array(
"status" => "t",
"message" => "Erfolgreich eingeloggt!",
"data" => $result
);
}
$con->close();
echo json_encode($response);?>
编辑 1:
一旦我使用dataType: 'json',我什么也没有收到(甚至没有收到字符串),所以我继续使用“文本”。我的 PHP 文件是否需要更改才能接收 JSON?
以下是我尝试过 cmets 的内容:
console.log(typeof d); 返回字符串
alert(JSON.stringify(d)); 返回"{\"status\":\"f\",\"message\":\"Benutzername und Passwort stimmen nicht ueberein\"}"
alert(JSON.parse(d)); 返回Uncaught SyntaxError: Unexpected token in JSON at position 0
还有什么推荐吗?谢谢!
【问题讨论】:
-
这个
dataType: "text",应该是dataType: "JSON", -
如果
JSON.parse(data)不起作用并且JSON.stringify(data)返回带有附加斜杠的数据,那么这表明您可能有一些字符(例如不可见的字符)可能会使 json 无效。console.dir(JSON.parse(data))出现什么错误,console.log(JSON.stringify(data))的输出是什么样的? -
尝试移动 $con->close();在 echo 之前尝试 console.log(typeof d);
标签: javascript php jquery json ajax