PHP echo,在对象(需要)之前输出完整的 html 代码(不需要)

PHP echo, outputting full html code (undesired) before object (desired)

本文关键字:不需要 代码 html 输出 echo 对象 PHP 需要      更新时间:2023-09-26

当我回显$jsonstring时,似乎一个完整的空白html页面被发送(从PHP到Javascript)与我请求的对象一起。 这里到处都是超级新的东西,所以我不明白为什么。

我的PHP代码:

<?php
//ini_set('display_errors', '1');
//ini_set('error_reporting', E_ALL);
require "localdbcxn.php";
$encoded = file_get_contents('php://input');
$decoded = json_decode($encoded, true);
$email = $decoded['email'];
$password = $decoded['password'];
$identify = mysql_query("SELECT UserId FROM users WHERE UserEmail='$email' AND UserPassword='$password'");
$numrows = mysql_num_rows($identify);
$row = mysql_fetch_assoc($identify);
$userid = $row['UserId'];
$sessionid = mt_rand(1111111111111111,9999999999999999);
$sessionkey = mt_rand(1111111111111111,9999999999999999);
$logindate = date("Y-m-d H:i:s");

$login = "INSERT INTO mobileSession (UserId, SessionId, SessionKey, BeginDate) VALUES('$userid','$sessionid','$sessionkey','$logindate') ON DUPLICATE KEY UPDATE  SessionId='$sessionid', SessionKey='$sessionkey', BeginDate='$logindate' ";
if ($numrows == 1) {
  mysql_query($login);
  $session = array('UserId'=>$userid,'SessionId'=>$sessionid);
  $jsonstring = json_encode($session);
  echo $jsonstring;
}
?>

以下是控制台(日志)显示的内容:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>Untitled Document</title>
</head>
<body>
</body>
</html>{"UserId":"33","SessionId":8207219793564744}

从用户ID到...4744 是正确的,但谁能帮助我理解为什么 html 代码被回显? 在我有限的经验中,我以前没有见过这种情况,觉得自己做错了什么。

谢谢!

必须在打印 JSON 数据之前指定内容类型。 在回显设置标头之前 -

header('Content-type: application/json');