为什么我的$getjson电话不起作用

Why doesn’t my $getjson call working?

本文关键字:电话 不起作用 getjson 我的 为什么      更新时间:2023-09-26

我对这个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+"");
        });
    });
});

测试.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。

首先确保你的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"} (