javascript - 全局范围、返回值和 ajax 的问题?

标签 javascript jquery ajax global-variables

标题是对我的脚本出了什么问题的猜测:

这是在我的 global.js 脚本中:

alert(search.getLabelsNames(); //alerts as undefined.
$('#search').autocomplete({
    source: function( request ) {
        search.getLabelsNames();
    },
    minLength:1
});

这是在我的 functions.js 脚本中:

var search;
window.search = {
    getLabelsNames:function( search ) {
        $.ajax({
            url : '../db_scripts/get_labels_names.php',
            type: "POST",
            data: { id: search }, //this defaults to nothing. not a problem
            success : function( data ) {
                var dataObj = jQuery.parseJSON( data );
                $.each(dataObj, function() {
                    alert(this.name);
                    return this.name;
                })
            }
        });
    }
}

在每个函数中,this.name 从数据库中正确返回每个标签名称。但是当我从 globals.js 调用它时,它返回为 undefined。如果我返回数字 1,search.getLabelsNames() 会警告 1..,因此查找全局函数没有问题。

这个脚本出了什么问题,为什么 global.js 找不到返回的 this.name

最佳答案

您有两个问题:

  1. 您无法从 jQuery.each 回调返回数据。返回值表示是否停止迭代。来自 documentation :

    We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

  2. 您无法从 Ajax 回调返回数据。 Ajax 是异步,这意味着在您的情况下,getLabelsNames 在检索和处理响应之前返回。

幸运的是,自动完成插件接受函数作为源。您已经在使用它,但没有正确使用。让它接受第二个参数,这是一个回调。来自 documentation :

The third variation, the callback, provides the most flexibility, and can be used to connect any data source to Autocomplete. The callback gets two arguments:

  • A request object, with a single property called "term", which refers to the value currently in the text input. For example, when the user entered "new yo" in a city field, the Autocomplete term will equal "new yo".

  • A response callback, which expects a single argument to contain the data to suggest to the user. This data should be filtered based on the provided term, and can be in any of the formats described above for simple local data (String-Array or Object-Array with label/value/both properties). It's important when providing a custom source callback to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.

因此,您需要做的就是将此回调传递给 getLabelsNames,以便可以在 Ajax 调用的 success 方法中调用它:

$('#search').autocomplete({
    source: function(request, callback) {
        // pass the callback along
        search.getLabelsNames(request.term, callback);
    },
    minLength:1
});

window.search = {
    getLabelsNames:function(search, callback) { // accept callback as argument
        $.ajax({
            url : '../db_scripts/get_labels_names.php',
            type: "POST",
            data: { id: search }, //this defaults to nothing. not a problem
            success : function( data ) {
                // format the data
                data = $.map(jQuery.parseJSON(data), function(obj) {
                    return obj.name;
                });
                // pass the data to the callback
                callback(data);
            }
        });
    }
}

请注意,我使用 jQuery.map [docs]在这里,从回调返回一个值具有不同的含义。不要将它与 jQuery.each 混淆。

关于javascript - 全局范围、返回值和 ajax 的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7123033/

相关文章:

javascript - 如何将 json 文件转换为 HTML 而无需先将它们添加到元素中?

javascript - 当用户单击链接时如何加密数据并在新选项卡中打开 PDF

jquery - 如何找到所有未选中的复选框?

javascript - AJAX中使用URL跳转到页面

javascript - JS AJAX 范围问题

javascript - Angular JS 将 html 页面嵌入为小部件

javascript - 获取表 td 中的输入值

javascript - 在我自己的 js 模板系统/引擎中使用 jquery 选择

javascript - 附加YouTube嵌入式视频标题

jquery - 为什么 AJAX 调用不起作用?