Ajax响应中的错误检查 [英] Error checking in Ajax Response
问题描述
我从API调用中获取了一个对象,我试图在将JSON数据呈现到视图之前进行错误检查.
I am getting a an object from my API call, i am trying to do an error checking before rendering the JSON data to my view.
function response(oResponse) {
if(oResponse && oResponse!= null
&& typeof oResponse === "object" && oResponse.responseCode !== null){
// you're getting data in JSON
// Use responseCode to proceed further
}
}
以下是我的 JSON
响应
{"code": "100", "responseCode":"444", :result: "successful"}
我想知道 if条件
是否正确?我是否在其中缺少某些东西,或者这是一个很大的状况.
I would like to know whether the if condition
is right or not? Am i missing something in it or is it a big condition.
推荐答案
您可以将条件简化为 oResponse&&oResponse.responseCode
(如果您关心的只是它不是 null
或 undefined
),并且具有 responseCode
属性,即不是 null
或 undefined
.
You can probably simplify the condition to oResponse && oResponse.responseCode
if all you care about is that it is not null
nor undefined
, and it has a responseCode
property that is not null
nor undefined
.
- 对
oResponse!= null
的检查是多余的,因为null
的评估结果为false
. - 出于相同的原因,对
oResponse.responseCode!== null
的检查是多余的. - 检查oResponse的
type ==="object"
是多余的,因为如果它是字符串或其他类型,则不会具有responseCode
属性. li>
- The check for
oResponse != null
is redundant sincenull
evaluates tofalse
. - The check for
oResponse.responseCode !== null
is redundant for the same reason. - The check for
typeof oResponse === "object"
is redundant since if it was a string or other type it wouldn't have aresponseCode
property.
请注意,如果 oResponse.responseCode === 0
或另一个"falsy"值,此条件将评估为false(即被认为是无效"的responseCode).
Note that if oResponse.responseCode === 0
or another "falsy" value, this condition will evaluate to false (i.e., that is considered an "invalid" responseCode).
@snowYetis关于错误处理程序的注释也是一个好主意,以防服务器上出现错误.它不会涵盖对无效的成功响应的验证.
@snowYetis comment about an error handler is also a good idea to have in there in case there is an error on the server. It won't cover the validation of a successful response that is invalid though.
这篇关于Ajax响应中的错误检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!