简体   繁体   English

$ .ajax回调函数无法正常工作

[英]$.ajax callback function is not working

I am just starting to learn JSON where a tutorial from other site uses this code (which I already modified to simplify this): 我刚刚开始学习JSON,其他网站的教程使用这个代码(我已经修改了这个代码):

$(document).ready(function(){
    $('#getdata-button').click(function(){
        $.ajax({
            type: "GET",
            url: "json-data.php",
            dataType: "json",
            success: function(){
                alert('a');
                $('#showdata').html(
                    "<p>item1="+data.item1+
                    " item2="+data.item2+
                    " item3="+data.item3+"</p>"
                );
            }
        });
    });
});

And this is the code for json-data.php 这是json-data.php的代码

<?php
    $item1 = "candy";
    $item2 = "chocolate";
    $item3 = "ice cream";

    //return in JSON format
    echo "{";
    echo "item1: ", json_encode($item1), "\n";
    echo "item2: ", json_encode($item2), "\n";
    echo "item3: ", json_encode($item3), "\n";
    echo "}";
?>

The problem is that alert function (for debugging purposes) isn't responding after I have clicked the button (with the id of "getdata-button"). 问题是,单击按钮(ID为“getdata-button”)后,警报功能(用于调试目的)没有响应。 Firebug says that the request is successful and I can see the data from there. Firebug说请求成功,我可以从那里看到数据。 No error was found. 没有发现错误。 It is just the callback function is not executing, but why? 它只是回调函数没有执行,但为什么呢?

You need to output your JSON correctly. 您需要正确输出JSON。 Replace your PHP with the below 用下面的PHP替换你的PHP

$items = array(
    'item1' => $item1,
    'item2' => $item2,
    'item3' => $item3
);
header('Content-type: application/json');
echo json_encode($items);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM