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

发布于 2024-11-30 13:52:31 字数 1118 浏览 0 评论 0原文

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

这是在我的 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

The title is a guess as to what is going wrong with my script:

This is in my global.js script:

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

This is in my functions.js script:

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;
                })
            }
        });
    }
}

In the each function, this.name, returns every one of the label names correctly from the database. But when I call it from globals.js, it returns as undefined. If I return the number 1, the search.getLabelsNames() alerts 1.. so it has no problem finding the global function.

what is wrong with this script and why can't global.js find the this.name that is being returned?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

不及他 2024-12-07 13:52:31

您有两个问题:

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

    <块引用>

    我们可以通过使回调函数返回 false 来在特定迭代中中断 $.each() 循环。返回非 false 与 for 循环中的 continue 语句相同;它将立即跳到下一次迭代。

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

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

第三种变体,即回调,提供了最大的灵活性,可用于将任何数据源连接到自动完成。回调获取两个参数

  • 一个请求对象,具有一个名为“term”的属性,它指的是当前文本输入中的值。例如,当用户在城市字段中输入“new yo”时,自动完成术语将等于“new yo”。

  • 响应回调,它期望单个参数包含向用户建议的数据。应根据提供的术语过滤此数据,并且可以采用上述简单本地数据的任何格式(具有标签/值/两个属性的字符串数组或对象数组)。提供自定义源回调来处理请求期间的错误非常重要。即使遇到错误,您也必须始终调用响应回调。这确保了小部件始终具有正确的状态。

因此,您需要做的就是将此回调传递给 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 [文档] 这里,返回的地方回调中的值有不同的含义。不要将它与 jQuery.each 混淆。

You have two problems:

  1. You cannot return data from a jQuery.each callback. The return value indicates whether to stop the iteration or not. From the 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. You cannot return data from an Ajax callback. Ajax is asynchronous, which means in your case that getLabelsNames returns before the response is retrieved and processed.

Luckily, the autocomplete plugin accepts a function as source. You are already using it, but not correctly. Make it accept the second argument, which is a callback. From the 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.

So what you have you have to do is passing this callback along to getLabelsNames so that it can be called in the success method of the Ajax call:

$('#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);
            }
        });
    }
}

Note that I use jQuery.map [docs] here, where returning a value form the callback has a different meaning. Don't confuse it with jQuery.each.

同展鸳鸯锦 2024-12-07 13:52:31

this 取决于调用的上下文。所以在你的内部函数中, this 是不一样的。

根据 dataObj 的结构,您可能想要执行以下操作:

$.each(dataObj, function(key, value) {
                alert(value.name);  // value will correspond to the current item being looped over
                return value.name;
            })

this depends on the context of the call. SO in your inner function, this isn't the same.

Depending on how your dataObj is structured, you may want to do something like:

$.each(dataObj, function(key, value) {
                alert(value.name);  // value will correspond to the current item being looped over
                return value.name;
            })
你在看孤独的风景 2024-12-07 13:52:31

AJAX 调用是异步的,这意味着您触发它们,它们稍后响应。您不能简单地从 ajax 调用“返回”一个值——您需要在“成功”时将一个值传递给另一个函数。

AJAX calls are asynchronous, meaning you fire them and they respond LATER. You can't simply "return" a value from an ajax call -- you need to pass a value to another function on "success".

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文