使用$ .getJSON方法和PHP

时间:2012-06-07 20:30:49

标签: jquery getjson

我正在尝试使用$ .getJSON函数来返回数据。我有以下html文件 命名为page.html

<!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>Request json test</title> 
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){

    $.getJSON("json-data.php",function(result){
     alert(result);
    });

  });

});
</script> 
</head>
<body>
<button>Get JSON data</button>
<div id="showdata"></div>
</body>
</html> 

我还有以下名为json-data.php的PHP文件:

<?php
//request data from the database
//code here to connect to database and get the data you want

/* Example JSON format 
{
  "item1": "I love jquery4u",
  "item2": "You love jQuery4u",
  "item3": "We love jQuery4u"
}
*/
$item1 = "I love jquery4u";
$item2 = "You love jquery4u";
$item3 = "We love jquery4u";
//return in JSON format
echo "{";
echo "item1: ", json_encode($item1), "\n";
echo "item2: ", json_encode($item2), "\n";
echo "item3: ", json_encode($item3), "\n";
echo "}";
?>

我只是尝试使用alert函数来查看PHP文件中的数据,但它不起作用。谁知道为什么?

谢谢, 吉姆

1 个答案:

答案 0 :(得分:2)

这是因为您的json格式无效:

$items = array("item1" => "I love jquery4u", "item2" => "You love jquery4u", "item3" => "jquery4u");

echo json_encode($items);