简体   繁体   中英

Difficulties using JSONP in jQuery

I've been reading up on JSONP and trying to get a working implementation. The code below represents my understanding of what this is supposed to look like using jQuery. For some reason I can't get this working, and I don't know why. I've seen many example scripts online, but for some reason, none of them work for me. Can anyone help? Am I doing this correctly?

Here's the JSONP script:

<script type="text/javascript">
$(document).ready(function() {
    var url =  "http://www.example.com/blog/?json=get_recent_posts";
    $.getJSON(url + "?callback=?", function(data) {
        $("#output_div").append("<p>" + data.posts[2].title + "</p>");
        }
    });
});
</script>

... and I wrote a div like this:

<div id="output_div"> </div>

Thanks!

Since callback is the second parameter you need to use & to append it to the url like url + "&callback=?" or

$(document).ready(function () {
    var url = "http://www.example.com/blog/?json=get_recent_posts&callback=?";
    $.getJSON(url, function (data) {
        $("#output_div").append("<p>" + data.posts[2].title + "</p>");
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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