在函数内部使用getJSON创建一个jQuery插件

时间:2015-03-01 06:09:14

标签: javascript jquery ajax json asynchronous

我不确定这是否是因为getJSON是异步的。我认为这是最明显的原因,但我不清楚它是如何工作的。在我的js文件中,我在body元素上调用healthCheck方法。什么都没发生。我的getJSON回调函数是否被调用?我不知道。

我已在JSFiddle上传了该脚本。

代码如下:

var baseURL = "http://someURL";
var id = "00000001";
var key = "0000aaaa-aa00-00a0-a00a-0000000a0000";
var healthcheck = "/version/healthcheck?";

( function($) {
        $.fn.healthCheck = function() {
            var timestamp = new Date().toJSON().toString();
            var request = healthcheck + "timestamp=" + timestamp + "&devid=" + id;
            var signature = CryptoJS.HmacSHA1(request, key);
            request = baseURL + request + "&signature=" + signature;
            $.getJSON(request, function(data) {
                var result = new Object();
                $.each(data, function(key, val) {
                    result.key = val;
                    if (val == false) {
                        this.innerHTML = "PTV API is currently not working. Error type: " + key + ".";
                    } else {
                        this.append(key + " working. <br />");
                    }
                });
            });
            return this;
        };
    }(jQuery));

非常感谢提前。我希望我的查询得到妥善处理。如果有人知道一些很好的资源,以便更好地理解jQuery中的异步方法,也会非常感激。我还没有找到很多很容易理解的东西。

1 个答案:

答案 0 :(得分:1)

尝试1)将jQuery.ajax( url [, settings ] )context设置为this的{​​{1}}; 2)在$.fn.healthCheck

创建对this对象的引用
$.each()

另见How do I return the response from an asynchronous call?

&#13;
&#13;
var baseURL = "http://someURL";
var id = "00000001";
var key = "0000aaaa-aa00-00a0-a00a-0000000a0000";
var healthcheck = "/version/healthcheck?";

(function($) {
        $.fn.healthCheck = function() {
            // set `this` object within  `$.getJSON`
            var timestamp = new Date().toJSON().toString();
            var request = healthcheck + "timestamp=" + timestamp + "&devid=" + id;
            var signature = CryptoJS.HmacSHA1(request, key);
            request = baseURL + request + "&signature=" + signature;
            $.ajax({
              url:request
            , type:"GET"
            , contentType: false
            , context: this
            , processData:false
            }).then(function(data) {
                // reference to `this` within `$.each()`
                var that = this; 
                var result = new Object();
                $.each(JSON.parse(data), function(key, val) {
                    result.key = val;
                    if (val == false) {
                        // `that` : `this`
                        that.innerHTML = "PTV API is currently not working. Error type: " + key + ".";
                    } else {
                        that.append(key + " working. <br />");
                        console.log("complete"); // notification
                    }
                });
            }, function(jqxhr, textStatus, errorThrown) {
                 console.log(textStatus, errorThrown); // log errors
            });
            return this;
        };
    }(jQuery));

$("body").healthCheck();
&#13;
var baseURL = "https://gist.githubusercontent.com/guest271314/23e61e522a14d45a35e1/raw/62775b7420f8df6b3d83244270d26495e40a1e9d/a.json";
var id = "00000001";
var key = "0000aaaa-aa00-00a0-a00a-0000000a0000";
var healthcheck = "/version/healthcheck?";

(function($) {
        $.fn.healthCheck = function() {
            var timestamp = new Date().toJSON().toString();
            var request = healthcheck + "timestamp=" + timestamp + "&devid=" + id;
            var signature = 123;// CryptoJS.HmacSHA1(request, key);
            request = baseURL + request + "&signature=" + signature;
            $.ajax({
              url:request
            , type:"GET"
            , contentType: false
            , context: this
            , processData:false
            }).then(function(data) {
                var that = this;
                var result = new Object();
                $.each(JSON.parse(data), function(key, val) {
                    result.key = val;
                    if (val == false) {
                        that.innerHTML = "PTV API is currently not working. Error type: " + key + ".";
                    } else {
                        that.append(key + " working. <br />");
                        console.log("complete"); // notification
                    }
                });
            }, function(jqxhr, textStatus, errorThrown) {
                 console.log(textStatus, errorThrown); // log errors
            });
            return this;
        };
    }(jQuery));

$("body").healthCheck()
&#13;
&#13;
&#13;