Send JSON to a variable outside the function

Asked

Viewed 47 times

1

My knowledge is vague in this area, I need a little help!

How do I get the result I received (JSON) and move to a variable. outside Function, I’m still learning.

But easy to post code, I have a JS that does all part of showing videos, Stories style.

Works normally like this:

<script>
var myPlaylist = [{"title": "Title","date": "11/8 2:34:4","url": "/stories/storie/0811201914357.mov","icon": "logo.jpg"}];

var socialStory = new Story({
	playlist: myPlaylist
});

</script>

But I already have an API that generates a JSON for me and I want to play in var myPlaylist, follows what I have so far, but I don’t know how to send the data to myPlaylist

<img class="profile" onclick="stories.launch();" src="logo.jpg" />
<div id="storytime"></div>
<script>
    function carrega(){
        var url = "stories.asp";
        $.ajax({
            type: "GET", 
            url: url,
            timeout: 3000,
            datatype: 'JSON',
            contentType: "application/json; charset=utf-8",
            cache: false,
            beforeSend: function() {
            },
            error: function() {
            },
            success: function(json) {

                    console.log(json.stories)
                    // me retorna assim
                    //{"title": "Title","date": "11/8 2:34:4","url": "/stories/storie/0811201914357.mov","icon": "logo.jpg"}
            } 
        });  
    }
    
    var myPlaylist = [?????????];

    var stories = new Story({
        playlist: myPlaylist
    });
</script>

I can’t change Stories.Launch, Tories and Story because JS is waiting for them. Can anyone help me? Thanks in advance for the great help!

  • what time you call the function carrega()?

1 answer

1

You can give a myPlaylist.push(json.stories), as myPlaylist is declared as an array in the main scope you can call it smoothly within its function.

would look that way in your code:

function carrega() {
        var url = "stories.asp";
        $.ajax({
            type: "GET",
            url: url,
            timeout: 3000,
            datatype: 'JSON',
            contentType: "application/json; charset=utf-8",
            cache: false,
            beforeSend: function () {
            },
            error: function () {
            },
            success: function (json) {

                myPlaylist.push(json.stories)
                console.log(myPlaylist)

            }
        });
    }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.