[SOLVED] How getJSON works

[SOLVED] How getJSON works
0

#1

Hello guys!
I have a big problem with getJSON and how it work. I try in this codepen to understand but i don’t recognize. Can someone help me?


#2

It seems like you’ve got it working. Do you have any questions in particular?


#3

You are need:
create function (click) for your button random.
:slight_smile:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
    $(document).ready(function() {

        $("button").click(function () {
            var url = "https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback="
            $.getJSON(url, function (a) {
                     $("#where").append(a[0].content + "<p>&mdash; " + a[0].title + "</p>");
            });
        });
       
    });
</script>
</head>
<body>

<button>Get JSON data</button>

<div id="where">teste</div>

</body>
</html>

#4

@PortableStick No, it doesn’t work.

@mederafael i try with your code, but it doesn’t work. What i wrong?


#5

I’m seeing a quote:

The only problem I see is this:

$('#where').text('hi'); // overwrites the fetched quote, delete this

#6

I put it to see if jQuery was working. I’m still on the default quote, and it doesn’t work. What i can do?


#7

I just looked at your Codepen. If you do not want the same quote added to the bottom of the previous, then you should replace append with html, so that instead of appending a quote, it will just replace the quote.


#8

Add this bit of code someone at the top of your script:

$.ajaxSetup({ cache: false });

#11

@RandellDawson he Api already gets random quote at every call. My “I need quotes from Api here.” doesn’t change in my codepen.

@PortableStick I’m in love. Can you explain me? Or give me something where i can take more information about this?


#12

I am not sure exactly what you want to happen when you click the button, but if you make the one change I mentioned above, it will replace everything in the div where id=“where” at each click of the button.


#13

cache (default: true, false for dataType ‘script’ and ‘jsonp’)
Type: Boolean
If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending “_={timestamp}” to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET.


#14

@RandellDawson i miss-read your post. I will change that, but the problem was about my cache.

@PortableStick tank you! You save me. So, i just need to delete my cache. :smile: