淘汰赛JS最佳实践阿贾克斯错误处理淘汰赛、错误、JS、阿贾克斯

2023-09-11 00:47:27 作者:摆摆手 祝你幸福

什么淘汰赛JS最佳实践,你使用时,AJAX,JSON响应回来不好。

What best practices for Knockout js have you used when ajax json responses come back bad.

你如何创建映射到显示发生错误给用户? 如何改变形式的结合在淘汰赛JS以适应错误?

How do you create your mappings to display an error has occured to the user? How do you change the binding of a form in Knockout js to accommodate errors?

我发回的响应对象{回应:成功,数据:{}},种这意味着有3个级别的错误的:

I send back a response object of {response:"success",data:{}}, which kind of means that there are 3 levels of error:

模型误差(失败的JSON对象的反应,以什么领域模型的数据是错误的) 服务器错误(服务器没有响应) 在服务器,错误code 响应

还没有想出显示这就是为什么我问一个错误消息的清洁视图模型的方式。

Have not figured out a clean viewmodel way of displaying an error message which Is why I'm asking.

推荐答案

我拿出错误处理KO是创建一个基类的方式:

The way I've come up with error handling in KO has been to create a base class:

errorHandlingViewModel = function () {
    var self = this;
    self.ErrorText = ko.observable();
    self.errorHandler = function (jqXHR, textStatus, errorThrown) {
        self.ErrorText('An error has occured, please refresh the page and try again in a little while. (' + textStatus + ':' + errorThrown + ')');
    };
    self.validationErrorHandler = function (err) {
        //todo
        alert('validation error ' + err);
    }
    self.successHandler = function (data, onSuccess) {
        if (data.result == "success") {
            if (onSuccess) {
                onSuccess(data.data);
            }
        }
        else {
            if (data.data && data.data.Tag) {
                if (data.data.Tag == "ValidationError") {
                    validationErrorHandler(data.data.Tag);
                }
            }
            errorHandler(null, data.result, data.data);
        }
    };
};

这有一个可观察ERRORTEXT场。

This has an observable ErrorText field.

我所有的ViewModels需要这种错误处理可以使用原型继承:

All my ViewModels that need this error handling can use prototypal inheritance:

viewModel.prototype = new errorHandlingViewModel();
var mainViewModel = new viewModel();
ko.applyBindings(mainViewModel, $("#locationTOApplyBindingTo")[0]);

在此视图模型Ajax调用是这样的:

In this view models ajax calls look like:

$.ajax({
    type: 'POST',
    url: myURL,
    data: myData,
    success: function (data) {self.successHandler(data,success);},
    error: self.errorHandler
}); //end ajax

用户界面是一个简单的数据绑定:

The UI is a simple data-bind:

<div class="error" data-bind="visible:ErrorText">
    <div class="innerMSGContainer">
        <div class="innerMSG" data-bind="text:ErrorText"></div>
    </div>
</div>

Javascript的尝试捕获仍然从这个模型中丢失,因为我不能确定的安置

Javascript Try-Catch is still missing from this model as I am unsure to the placement

 
精彩推荐
图片推荐