Ajax调用范围$。异步请求

时间:2018-08-03 11:21:47

标签: javascript ajax

我正在使用一个名为“ jquery-comments”的库。它以这种方式初始化:

var commentsArray = [bla bla bla];
jQuery(function($){
    $('#comments-container').comments({
        getComments: function(success, error) {
            setTimeout(function() {
                success(commentsArray);
            }, 500);
        }
    });
});

一切正常,但现在我想从URL异步加载“ commentsArray”。我尝试这样做:

var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        var commentsArray = JSON.parse(xmlHttp.responseText);
        jQuery(function($){
            $('#comments-container').comments({
                getComments: function(success, error) {
                    setTimeout(function() {
                        success(commentsArray);
                    }, 500);
                }
            });
        });
    }
}
xmlHttp.open("GET", "/getComments", true);
xmlHttp.send(null);

它给了我错误:

jQuery.Deferred exception: $(...).comments is not a function.

我理解这是因为我是从嵌套函数的作用域中调用它的,但是我自己找不到解决方案。如何防止此错误并使其异步加载?

2 个答案:

答案 0 :(得分:0)

我自己找到了解决方案。 万一这对某人有用:

var nastyObject = null;
jQuery(function($){
    nastyObject = $('#comments-container');

    var xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = function() {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
            var commentsArray = JSON.parse(xmlHttp.responseText);
            nastyObject.comments({
                getComments: function(success, error) {
                    setTimeout(function() {
                        success(commentsArray);
                    }, 500);
                }
            });
        }
    }
    xmlHttp.open("GET", "/getComments", true);
    xmlHttp.send(null);
});

答案 1 :(得分:-1)

确保首先加载了 pts rule name description ---- ---------------------- -------------------------------------------------- 0.00 HTML_IMAGE_ONLY_08 BODY: HTML: images with 400-800 bytes of words 0.00 HTML_MESSAGE BODY: HTML included in message 0.00 MIME_QP_LONG_LINE RAW: Quoted-printable line longer than 76 chars 0.82 MIME_QP_LONG_LINE_2 RAW: Quoted-printable line longer than 76 chars 1.78 HTML_IMAGE_ONLY_08_2 HTML: images with 400-800 bytes of words 库。

由于您使用的是jQuery,因此也将其用于Ajax:

.comments
相关问题