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

时间:2015-11-24 13:50:58

标签: javascript jquery html jsonp getjson

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

工作正常(在$(文件).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>

不工作(在$(&#39;#btn1&#39;)下(&#39;点击&#39;,功能()

<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>

1 个答案:

答案 0 :(得分:2)

这不起作用,因为你把按钮放在表格中

<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