JSON解析未从数组中获取值


JSON parse not getting value from array

我正在对PHP函数返回的数组执行JSON解析,但它似乎不起作用。

以下是PHP函数:

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
			$bname = $_REQUEST["bname"];
        	$link = mysqli_connect('localhost', 'root', '123'); 
			$servername = "localhost";
			$username = "root";
			$password = "123";
			$dbname = "success";
			// Create connection
			$conn = new mysqli($servername, $username, $password, $dbname);
			// Check connection
			if ($conn->connect_error) {
    			die("Connection failed: " . $conn->connect_error);
			}
			// PHP for execution
			$sql = "SELECT id, bname, bicon, rafrica, rasia, roceania, reurope, rsouthamerica, rnorthamerica, traffic, revenue, profit FROM business LIMIT 1";
			$result = $conn->query($sql);
			if ($result->num_rows > 0) {
    			// output data of each row
    			while($row = $result->fetch_assoc()) {
        			$b3name = $row["bname"]. "<br>";
        			$b3icon = $row["bicon"]. "";
        			$b3rafrica = $row["rafrica"]. "<br>";
        			$b3rasia = $row["rasia"]. "<br>";
        			$b3roceania = $row["roceania"]. "<br>";
        			$b3reurope = $row["reurope"]. "<br>";
        			$b3rsouthamerica = $row["rsouthamerica"]. "<br>";
        			$b3rnorthamerica = $row["rnorthamerica"]. "<br>";
        			$b3traffic = $row["traffic"]. "<br>";
        			$b3revenue = $row["revenue"]. "<br>";
        			$b3profit = $row["profit"]. "<br>";
    			}
			} else {
    			echo "0 results";
			}
			$output = array(
			    'name' => $b3name,
			    'icon' => $b3icon,
			    'traffic' => $b3traffic
			);
			
			echo json_encode($output);
?>
</body>
</html>

以下是包含JSON解析的AJAX:

		function loadfacebook1()
		{
			var xmlhttp;
			if (window.XMLHttpRequest)
  			{// code for IE7+, Firefox, Chrome, Opera, Safari
  			xmlhttp=new XMLHttpRequest();
  			}
			else
  			{// code for IE6, IE5
  			xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  			}
			xmlhttp.onreadystatechange=function()
			  {
			  if (xmlhttp.readyState==4 && xmlhttp.status==200)
			    {
			    document.getElementById("b1").innerHTML=xmlhttp.responseText;
			    }
			  } 
 			
 			xmlhttp.open("GET","getfacebook.php",true);
			xmlhttp.send();
			var obj = JSON.parse(xmlhttp.responseText);
			document.getElementById("demo").innerHTML=obj.name + "<br>";
		}

我正在使用

<span id="demo">

以显示返回的值,但我需要将obj.name(以及数组的一些其他元素)分配给一个变量,我可以使用该变量来更新页面中的其他内容。如有任何帮助,我们将不胜感激。

干杯,

是否

您应该将接收到的JSON的解析转移到AJAX响应(onreadystatechange)传递时调用的函数

当您从PHP提供JSON结果时,您应该排除HTML代码。尝试删除以下内容,看看它是否有帮助:

<!DOCTYPE html>
<html>
<head>
</head>
<body>

</body>
</html>