3

我的 Web 应用程序中有一个文档列表。我允许用户创建新文档。当他们单击“新建”时,文档快捷方式的严格客户端实例会显示为焦点空白标题字段。然后他们输入标题并单击保存。在视图模型中,这是 save 所做的:

var document = new documentViewModel(dataservice.createDocument(newData)); // calls ajax method below with new document's data to POST back
innerModel.documents.remove(item);
innerModel.documents.push(document); 

我删除占位符文档 ( item) 并推送新的真实数据document。但就目前而言,文档只是一个空白项,在异步调用的真实数据返回之前被推送,因此没有真实数据被推送。

Save向端点发送 jquery 调用:

   var options = {
            url: saveEndpoint,
            type: 'POST',
            dataType: 'json',
            data: newDocument,
            xhrFields: {
                withCredentials: true
            }
        };

        return $.ajax(options)
            .done(function (response) {
                return response;
            })
            .fail(function (msg) {
                toastr.error("Error: Could not create document.");
            });

就目前而言,这是行不通的,因为真实数据永远不会进入视图。

以这种方式使用异步调用创建新项目的标准方法是什么?我应该让它成为一个同步调用吗?还是有一个我不知道的中间立场?任何帮助将非常感激。

4

1 回答 1

1

您的数据服务未正确处理 ajax 调用。 $.ajax()不返回请求的结果,您需要将回调方法传递给它,以便它知道在请求完成时要做什么。

dataservice.createDocument应该看起来像:

createDocument(newDocument, handleResponse) {
    var options = {
        url: saveEndpoint,
        type: 'POST',
        dataType: 'json',
        data: newDocument,
        xhrFields: {
            withCredentials: true
        }
    };

    $.ajax(options)
        .done(function (response) {
            // this is the callback method that gets passed in
            handleResponse(response);
        })
        .fail(function (msg) {
            toastr.error("Error: Could not create document.");
        });
}

并像这样调用:

// the function in the argument is the callback method that will be executed
// when the ajax request is completed
dataservice.createDocument(newData, function (document) {
    var document = new documentViewModel(document);
    innerModel.documents.remove(item);
    innerModel.documents.push(document); 
});

有关更多示例和解释,请参阅这些其他问题:

于 2013-07-07T03:19:27.400 回答