【问题标题】:JQuery getJson success function is firing on button clickJQuery getJson 成功函数在按钮单击时触发
【发布时间】:2016-02-26 23:57:50
【问题描述】:

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

工作正常(在 $(document).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').on('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>

【问题讨论】:

    标签: javascript jquery html jsonp getjson


    【解决方案1】:

    它不起作用,因为您将按钮放入表单中

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

    它会在你每次点击时提交,在其他意义上它会重新加载页面。

    只需在表单中定义按钮的类型。

    这样试试

    <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

    【讨论】:

    • 它现在工作正常,谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-31
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多