Why doesn't this show JSON data in the console log using jquery?

When I encode this in some file (say: test.html):

<html>
<head>
    <title>Test</title>
</head>
<body>
 <script src="https://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
    $.getJSON('https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=my-api-key',function(json) {
        console.log(json);

    });
</script>
</body>
</html>

But if I do the same in another file, say (main.js)

(function(){

$.getJSON('https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=my-api-key',function(json) {
        console.log(json);

    });

});

The above code does not display JSON data on the console, I added main.js in the HTML.

+4
source share
2 answers

Because in the second fragment the function is not performed at all.

Code below

(function(){
     $.getJSON('... url ...', function(json) {
         console.log(json);
     };
});

Can be simplified in

(function(){});

Which is not performed at all. You need to put the brackets at the end of the function being executed, for example:

(function(){}());

Or even better, use a ready-made jquery document to execute correctly after the page loads.

$(function(){});

Hope this helps.

+4
source

, main.js. function() {}, , , . , .

(function(){

  $.getJSON('https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=045089075bc74354be01b34f6335d32b',function(json) {
      console.log(json);
  });

})(); // parenthesis call the function
+1

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


All Articles