为什么我的$ getjson调用不起作用?

时间:2015-11-28 15:03:03

标签: javascript php getjson

我对这个php比较新,我试图从我的javascript文件中访问/执行一个php文件并将其显示在我的html中。我被告知$ getjson是最好的方法,但我没有看到我的PHP脚本过去支持我的HTML:

HTML:

<!doctype html>
<html lang="en">

<head>
    <div class="button"></div>
    <script src="http://code.jquery.com/jquery-1.7.js"></script>
    <script src="Test.js" type="text/javascript"></script> 
</head>
<body>
     <a href="#" id="getdata-button">Get JSON Data</a>
    <div id="showdata"></div>
</body> 

</html>

使用Javascript:

$(document).ready(function(){
    $( document ).on("click","#getdata-button", function() {
    //test Confirmed
    alert('hello8');
       $.getJSON('Test.php', function(data) {
            //noresponse
            alert('hello5');
            $('#showdata').html("item1="+data.item1+" item2="+data.item2+" item3="+data.item3+"");
        });
    });
});

test.php的:

    < ?php
$items = array( 
  'item1' => 'I love jquery4u',
  'item2' => 'You love jQuery4u',
  'item3' => 'We love jQuery4u'
);

header('Content-type: application/json');
echo json_encode($items);

?>

我的预期结果是html中的item1 / item2 / item3。

1 个答案:

答案 0 :(得分:1)

首先确保您的javascript代码确实被触发/执行 http://api.jquery.com/live/说:

从jQuery 1.7开始,不推荐使用.live()方法。使用.on()附加事件处理程序。旧版jQuery的用户应该使用.delegate()而不是.live()。

然后使用

之类的东西
<?php // no space between < and ? or php
$items = array( 
  'item1' => 'I love jquery4u',
  'item2' => 'You love jQuery4u',
  'item3' => 'We love jQuery4u'
);
// the (configuarable) default for the content-type is text/html
// -> let the client "manually" know the response is json
header('Content-type: application/json');
echo json_encode($items);

作为服务器端脚本。 (打印:{"item1":"I love jquery4u","item2":"You love jQuery4u","item3":"We love jQuery4u"}