How to pass external JSON file to javascript variable accessible anywhere

I have a json file that I used in my project in this structure

<script src="js/main.js"></script>

<script>    
    var data = {"bills":[{"id":1,"name":"DStv","reference":"SmartCard Number","logo":"bill\/logo\/24Io6IqObQ8ddi5.jpg","active":1,"lifestyle":0},{"id":3,"name":"GOtv","reference":"IUC Number","logo":"bill\/logo\/mCNl5X1ZCfph4kg.jpg","active":1,"lifestyle":0},{"id":6,"name":"Startimes"...
</script>

<script src="js/bill.js"></script>
<script src="js/airtime.js"></script>

As you can see from the above example, the json file is already transferred to the data variable ... from which I have another external javascript file located under it.

Meanwhile, the json file is now created for reference, and I was told to use ajax to get json data in the project.

I have this code in my main.jsfile, I have the code below, but it is not available in the filebills.js

$(document).ready(function () {

   $.ajax({
       type: "GET",
       url: "http://bills.payit.ng/bills/resources",
       success: function(result)
       {
           data = result;
           loadData(result);

       }
   });

});
+4
source share
2 answers

, Javascript cookie , , -

 $.ajax({
       type: "GET",
       url: "http://bills.payit.ng/bills/resources",
       success: function(result)
       {
           data = result;
           setCookie("myStaticDataPerDay",data,1)
           loadData(result);

       }
   });
});

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}

console.log(getCookie("myStaticDataPerDay"));
function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

jquery cookie

$.ajax({
       type: "GET",
       url: "http://bills.payit.ng/bills/resources",
       success: function(result)
       {
           data = result;
           $.cookie('myStaticData', data);
           loadData(result);

       }
   });
});

var data=JSON.parse($.cookie("MyStaticData"))

localStorage , IOS, ios cookie

+1

:

// in ajax success
var event = new CustomEvent("custom-event", {data: result});
window.dispatchEvent(event);

bill.js script , :

window.addEventListener("custom-event", function(e) {
  console.log("custom-event", e.data);
});
0

Source: https://habr.com/ru/post/1693229/


All Articles