【问题标题】:ajax can not receive JSON from phpajax 无法从 php 接收 JSON
【发布时间】: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


【解决方案1】:

试试这个

$.ajax({
    url: 'http://localhost/weltenbummler/Weltenbummler1/Weltenbummler1/app/login.php?username=' + name + '&password=' + pass,
    dataType: 'json',
    type: 'get',
    success: function (e) {
        alert( JSON.parse(e.message) ); // undefined
    }
});

【讨论】:

  • 对于问题e.message中显示的数据是文本而不是JSON,OP为什么要尝试解析它?如果返回的数据被正确识别为 JSON,那么e 将已经保存了解析的对象。
  • 如果数据类型是文本,他可以只做“alert(e)”,op 说,它的 json,所以他/她需要解析以便将返回数据转换为适当的 javascript 对象。
  • 是的,但是 OP 说 alert(d); 显示 JSON 字符串,alert(d.message); 显示 undefined。所以如果dataType: 'json' 会纠正返回的数据没有被jQuery 解析的问题,那么JSON.parse(e.message) 会尝试解析不是JSON 的"Benutzername und Passwort stimmen nicht ueberein"。如果它不能解决问题,d.message 仍然是undefined,JSON.parse(e.message) 会因为解析undefined 而显示错误。
  • 遗憾的是,这不起作用......一旦我将 dataType 更改为“json”,我什么也没有收到,甚至连字符串都没有。使用“文本”我得到了字符串,但是 '( JSON.parse(e.message) );' 的警报//什么都没发生
【解决方案2】:

您可以通过 chrome 开发人员读出准确的接收数据: 1. 我收到一个带有隐藏变量的字符串:#$63434;{"status":false,...} 和 2. 还有 PHP 错误

到 1.: PHP 缓冲变量触发你的代码 --> 使用 ob_start(); 和 ob_end_clean(); 限定它 参考:https://stackoverflow.com/a/9985307/8036245

至 2.:只需修复您的 php 代码:我遇到了问题,未定义的变量警告缺少参考

之后我什至可以调用 $.getJSON(..) ! 希望这会帮助somone :)

【讨论】:

    【解决方案3】:
    • contentType 是发送到服务器的标头,指定特定格式。 示例:我正在发送 json 或 XML
    • dataType 你是在告诉 jQuery 期待什么样的响应。 期待 JSON,或 XML,或 HTML 等......默认它让 jQuery 尝试找出它。

    $.ajax() documentation 也有这些的完整描述。

    $.ajax({
        url: "http://localhost/weltenbummler/Weltenbummler1/Weltenbummler1/app/login.php?username=" + name + "&password=" + pass,
        dataType: 'JSON',
        type: 'GET',
        success: function (d) {
            console.log(JSON.parse(d.message))
        },
    });
    

    【讨论】:

    • 对于问题 d.message 中显示的数据是文本而不是 JSON,OP 为什么要尝试解析它?如果返回的数据被正确识别为 JSON,那么d 将已经保存了解析的对象。
    【解决方案4】:
    echo json_encode($response, true);
    

    【讨论】:

      猜你喜欢
      • 2010-09-09
      • 1970-01-01
      • 1970-01-01
      • 2021-01-30
      • 1970-01-01
      • 1970-01-01
      • 2013-05-15
      • 2013-07-28
      • 1970-01-01
      相关资源
      最近更新 更多