简体   繁体   English

从php文件中使用.getJSON检索JSON数据

[英]Retrieving JSON data with .getJSON from a php file

I've got a problem with sending json data. 我在发送json数据时遇到问题。

Here's my php file: 这是我的php文件:

<?php
session_start();
$con = mysql_connect("localhost","root","");
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("db", $con);
$result_array = array();
$result = mysql_query("SELECT Reg FROM bool");

while ($row = mysql_fetch_array($result)) 
$result_array[] = $row;


echo json_encode($result_array);
mysql_close($con);
?>

And here's my js script: 这是我的js脚本:

$(function () {
    $(document).ready(function() {
    $.getJSON("sql_bool.php", function(data) {
    alert(data[1]);     
    });    
});    
});

I've got some bool data stored in my database, and when i try to check with an alert() function if it made it through, all i get is an alert window with 我已经在数据库中存储了一些布尔数据,当我尝试使用alert()函数检查是否通过时,我得到的只是一个带有警告窗口

[object Object]

Any idea what's wrong? 知道有什么问题吗?

It sounds like it went through fine. 听起来好像一切顺利。 When you alert in JavaScript it turns whatever you alert into a string. 当您使用JavaScript发出警报时,它将警报内容转换为字符串。 In this case your object as a string would be [ object object]. 在这种情况下,您的对象作为字符串将是[object object]。

You could try: 您可以尝试:

for(var k in data[1]){ alert(k); for(var k in data [1]){alert(k); alert(data[1][k]); 警报(数据[1] [K]); } }

What you get back is a JSON encoded object. 您得到的是一个JSON编码的对象。 If you give that to javascript using getJSON it will handle it like an object. 如果使用getJSON将其提供给javascript,它将像对象一样处理它。 If you want to see the actual string you got back from the server, you could try this: 如果要查看从服务器返回的实际字符串,可以尝试以下操作:

alert(JSON.stringify(data));

That should output everything you got back from the PHP script in a readable manner :) 这应该以一种可读的方式输出您从PHP脚本获得的所有内容:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM