javascript – JQuery getJson成功函数在点击按钮时触发

我无法解决getjson成功事件.当我在$(document).ready上调用$.get
JSON时,它的工作正常,当我在按钮下单击相同的代码时,它就无法正常工作.

工作正常(在$(文件).ready下)

<html>
<head>
<title>API Logger</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js" ></script>
    <script>
        "use strict";
        $(document).ready(function(){
                var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
                $.getJSON( flickerAPI, 
                {
                    tags: "mount everest",
                    tagmode: "any",
                    format: "json"
                },
                function(data)
                {
                    alert("success");

                });
        });
    </script>
</head>
    <body>
        <form>
            <button id="btn1" >Execute</button>
        </form>
    </body>

不工作(在$(‘#btn1’)下.(‘click’,function()

<html>
<head>
<title>API Logger</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js" ></script>
    <script>
        "use strict";
        $(document).ready(function(){
            $('#btn1').on('click', function() {

                var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
                $.getJSON( flickerAPI, 
                {
                    tags: "mount everest",
                    tagmode: "any",
                    format: "json"
                },
                function(data)
                {
                    alert("success");

                });

            });
        });
    </script>
</head>
    <body>
        <form>
            <button id="btn1" >Execute</button>
        </form>
    </body>

最佳答案 它没有用,因为你把按钮放在窗体中

<form>
    <button id="btn1" >Execute</button>
</form>

它会提交evertime你点击其他意义上它会重新加载页面.

只需在表单中定义按钮类型即可.

试试这样吧

<form>
    <button type="button" id="btn1" >Execute</button>
</form>

JSFIDDLE

或者只是在点击事件中添加return false

$(document).ready(function () {
    $('#btn1').on('click', function () {
        var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
        $.getJSON(flickerAPI, {
            tags: "mount everest",
            tagmode: "any",
            format: "json"
        }, function (data) {
            alert("success");
        });
        return false;
    });
});

JSFIDDLE

点赞