【发布时间】:2015-06-03 14:52:44
【问题描述】:
我想将$.ajax().done() 包装在一个单独的类中,其中包括针对模式验证 JSON 响应。
示例调用可能如下所示:
myService.get("/api/people").done(function(people) {
// at this point I'm certain the data in people is valid
template.render(people);
}).catch(function() {
// this happens if validation of people failed, even if the request itself was successfull
console.log("empty json or validation failed");
});
成功回调函数在done() 中传递,但仅应在私有函数(_validate(data, schema)) 返回 true 时执行。不太优雅的版本可能如下所示:
myService.get("api/people", successCallback, errorCallback);
我想直接暴露$.ajax()的内部Deferred方法。这可能吗?
【问题讨论】:
-
您有一个
GET,它可能会返回无效数据?我错过了什么吗?这听起来很疯狂。 -
@Mathletics 这一点都不疯狂。 在野外 请求将随机失败。例如,您将只获得身体的一部分,您可能会从服务器获得 404 或 500,或者您可能会失去连接。
-
myService.get("api/people").then(successCallback, errorCallback);??? -
@Mathletics JSON 请求本身可能成功,但我想根据一组标准验证响应对象。
-
@Halcyon 但任何一种情况都是请求错误,并会触发相应的处理程序。 OP 表示请求将成功,但实际响应可能包含无效数据(不是损坏/坏数据,只是不适合客户端某些架构的数据。)
标签: javascript jquery ajax promise jquery-deferred