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

时间:2022-10-17 10:22:38

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

我有一些bool数据存储在我的数据库中,当我尝试使用alert()函数检查它是否通过时,我得到的是一个警报窗口

[object Object]

Any idea what's wrong?

知道什么是错的吗?

2 个解决方案

#1


1  

It sounds like it went through fine. When you alert in JavaScript it turns whatever you alert into a string. In this case your object as a string would be [ object object].

听起来好像很顺利。当您在JavaScript中发出警报时,它会将您提醒的内容转换为字符串。在这种情况下,您的对象作为字符串将是[对象对象]。

You could try:

你可以尝试:

for(var k in data[1]){ alert(k); alert(data[1][k]); }

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

#2


0  

What you get back is a JSON encoded object. If you give that to javascript using getJSON it will handle it like an object. If you want to see the actual string you got back from the server, you could try this:

你得到的是一个JSON编码对象。如果你使用getJSON将它赋予javascript,它将像对象一样处理它。如果你想看到你从服务器回来的实际字符串,你可以试试这个:

alert(JSON.stringify(data));

That should output everything you got back from the PHP script in a readable manner :)

这应该以可读的方式输出您从PHP脚本返回的所有内容:)

#1


1  

It sounds like it went through fine. When you alert in JavaScript it turns whatever you alert into a string. In this case your object as a string would be [ object object].

听起来好像很顺利。当您在JavaScript中发出警报时,它会将您提醒的内容转换为字符串。在这种情况下,您的对象作为字符串将是[对象对象]。

You could try:

你可以尝试:

for(var k in data[1]){ alert(k); alert(data[1][k]); }

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

#2


0  

What you get back is a JSON encoded object. If you give that to javascript using getJSON it will handle it like an object. If you want to see the actual string you got back from the server, you could try this:

你得到的是一个JSON编码对象。如果你使用getJSON将它赋予javascript,它将像对象一样处理它。如果你想看到你从服务器回来的实际字符串,你可以试试这个:

alert(JSON.stringify(data));

That should output everything you got back from the PHP script in a readable manner :)

这应该以可读的方式输出您从PHP脚本返回的所有内容:)