开发者

Creating a helper method with jquery/json/getJSON

开发者 https://www.devze.com 2023-02-24 07:44 出处:网络
I wanted to create a helper method that can be contained in an included javascript and referenced easily.The helper method wraps the .getJSON function from jquery ...

I wanted to create a helper method that can be contained in an included javascript and referenced easily. The helper method wraps the .getJSON function from jquery ...

function doSomething(someThing) { 
  $.getJSON(theCoolestURLEver, {auth_key:"barfoo", id:someThing}, function(data) {
   console.log(data);
   return data;
  });
}

In my normal HTML pages, what I want to do is:

<html>
<head>
   <script src="/_/js/myCoolFunctions.js"></script>
</head>
<body>
<script>
  var someThing = "foobar";
  var data = doSomething(someThing);
  console.log(data);
</script>
</body开发者_高级运维>
</html>

The end result is that the console.log comes back as undefined in the second block of code. I understand now that this has to do with scope or that the page loads and the data isn't available when the < script > tag loads. So ... if this is true, how do I create a helper method that can hide some complexity that occurs ALL the time? Like adding the auth_key ...


The problem is that AJAX requests (such as $.getJSON) are asynchronous. That means that the function call returns immediately, before the request has completed. You're providing a callback -- this function is run after the data is received; this will be after the console.log.

(As an additional point, the return only sets the return value of the handler, not the doSomething function.)

The best way round this would be, I think, to create your own helper method:

$.getJSONAuth = function(url, data, success) {
    var authData =  {auth_key:"barfoo"};

    if ($.type(data) === 'function') {
        success = data;
        data = authData;
    } else {
        data = $.extend({}, authData, data);
    }

    return $.ajax({
        url: url,
        type: 'GET',
        dataType: 'json',
        success: success,
        data: data
    });
}

You could now call this as so:

$.getJSONAuth(theCoolestURLEver, {id:someThing}, function(data) {
    console.log(data);
});


Your doSomething function does not return anything, the callback function of getJSON does. getJSON is executed async, so your doSomething function ends, before the request is completed. You can pass a function to your doSomething function however:

function doSomething(someThing, callback) { 
  $.getJSON(theCoolestURLEver, {auth_key:"barfoo", id:someThing}, function(data) {
   callback(data)
   return data;
  });
}

And call it like this:

<script>
  var someThing = "foobar";
  doSomething(someThing, function(data) { console.log(data); });
</script>


What if you do:

$.getJSON(theCoolestURLEver, {'auth_key:"barfoo"', 'id:someThing'}, function(data)

Note the ' symbols rounding the json keys. I don't know, but it's how I 'd do it.

0

精彩评论

暂无评论...
验证码 换一张
取 消