Javascript, php, mysql, and json has me stumped
Been reading up on php and json and am trying this piece of code which is not working and I can't figure out why. Any help is appreciated.
I call a JavaScript function from my html file onLoad(). That function is
function getSched()
{
$.post("schedlz.php", {dat: ""+inputString+"", action: "searchSched"}, function(data)
{
var y="";
if(data.length >0)
{
var obj = JSON.parse(data);
y = getRes (data);
}
else //some error handler
}
function getRes(data)
{
var str="";
var obj = JSON.parse (data);
alert (data.length + " | " +obj + " | ");
return str;
}
In schedlz.php file
$conn = getDbConn();
mysql_select_db("myschedulez", $conn);
$result = mysql_query($sql,$conn) or die('Error: ' . mysql_error());
$rows = array();
while ($r = 开发者_如何学运维mysql_fetch_assoc($result))
{
// $rows['schedulez'][] = $r;
$rows[] = $r;
}
echo json_encode($rows);
mysql_close($conn);
The problem is that I get the data back in correct json format but when I parse it, there is no Object. What could be going wrong here?
You need to add the dataType
parameter to your $.post
, which in your case is json
.
I'm also not sure if you closed $.post
correctly in your sample so I'm adding the closing );
as well.
function getSched()
{
$.post("schedlz.php",
{dat: ""+inputString+"", action: "searchSched"},
function(data) {
var y="";
if(data.length >0)
{
var obj = JSON.parse(data);
y = getRes (data);
}
else {} //some error handler
},
'json'
);
}
精彩评论