函数返回后,AJAX请求返回值

时间:2014-02-14 20:04:23

标签: javascript ajax knockout.js

我有一个Knockout绑定到我的函数:

<tr id="toolbarRow" data-bind="foreach: get_tabs()">

get_tabs调用load,它使用ajax请求填充departments变量:

get_tabs = function () {
    load();
    return departments;
},

这导致了一个问题,因为get_tabsdepartments填充load之前返回load

这是load = function () { $.ajax( { url: _spPageContextInfo.webAbsoluteUrl + "/_api/search/query?querytext='Department:*" + "*'&selectproperties='Department'&sourceid='B09A7990-05EA-4AF9-81EF-EDFAB16C4E31'&sortlist='Department:ascending'", method: "GET", headers: { "accept": "application/xml", }, success: onSuccess, error: onError } ); }, onSuccess = function (data) { ...populating departments variable... }, onError = function (err) { alert("something blew up"); },

get_tabs

在我的ajax请求完成onSuccess事件之前,如何让{{1}}不再返回?

4 个答案:

答案 0 :(得分:2)

正如评论所指出的,you can't expect to be able to return data from an AJAX request。通常,您提供的回调函数在检索结果后可以正常工作。

使用KnockoutJS时执行此操作的正确方法是使用 observable array 。在viewmodel中将属性声明为可观察数组,将一些HTML数据绑定到它,然后在需要时填充数据。这是一个简单的例子:

function MyViewModel() {
    this.departments = ko.observableArray([]);
    this.load = function () {
        $.ajax({
            /* your AJAX options */
        })
        .success(this.departmentsLoaded.bind(this))
    };

    this.departmentsLoaded = function (data) {
        this.departments(data);
    };
}

您的视图/标记看起来像这样:

<div data-bind="foreach: departments">
    <span data-bind="text: $data"></span>
</div>
<button data-bind="click: load">Load</button>

示例: http://jsfiddle.net/CCNtR/113/

答案 1 :(得分:1)

你变暖了。 $ .ajax立即返回。您需要做的是在$ .ajax调用中使用您的成功处理程序来响应服务器返回的数据。

这就是我要做的事情:

get_tabs = function(callback) {
    load(callback);
}
load = function(callback) {
    $.ajax({
        ...,
        success: function(data) {
            // populate departments data
            callback.apply(this, arguments);
        }
    });
}

答案 2 :(得分:1)

为什么不让部门成为一个可观察的数组并直接绑定到那个?无需回调。你会做类似的事情:

 <tr id="toolbarRow" data-bind="foreach: departments">

function myViewModel()
{
    var self = this;

    self.departments = ko.observableArray();

    //call the following in your document ready 
    myViewModel.prototype.load = function () 
    {
        $.ajax(
        { //make your ajax call


            success: function (result,status,xhr)
            {
                ...populating departments variable...
            }
        });   
    }
}

$(document).ready(function()
{
    //Toolbar will be empty because departments is empty at this point.
    ko.applyBindings(myViewModel);

    //Your onSuccess handler will populate the departments observable array
    //when it changes, your toolbar will populate. No need for callbacks.
    myViewModel.load();
}

这真的是knockoutjs的美妙之处在于你不必担心处理这样的东西......很多; - )

答案 3 :(得分:-2)

您需要在departments函数

内返回onSuccess()
 onSuccess = function (data) {
    return departments;
},
相关问题