jQuery Ajax回调数组结果
我遵循jQuery Ajax
场景,其中webmethod返回字符串集合。
- 该集合可以为null
- 该集合可以是非空但是零记录。
- 该集合有一个或多个记录
以下代码工作正常。 它使用jQuery.isEmptyObject 。 当它不是Plain Object
时,建议不要使用isEmptyObject()
。
如何在不使用isEmptyObject()的情况下处理结果?
注意:ajax“结果”是“不明白”。
参考:
- 对象是空的吗?
- Javascript的hasOwnProperty()方法比IN运算符更一致
码
//Callback Function function displayResultForLog(result) { if (result.hasOwnProperty("d")) { result = result.d } if ($.isPlainObject(result)) { alert('plain object'); } else { alert('not plain'); } if($.isEmptyObject(result)) { //Method returned null $(requiredTable).append('No data found for the search criteria.'); } else { if (result.hasOwnProperty('length')) { //Set the values in HTML for (i = 0; i < result.length; i++) { var sentDate = result[i]; } } else { //Method returned non-null object; but there is no rows in that $(requiredTable).append('No data found for the search criteria.'); } } } function setReportTable(receivedContext) { var searchInput = '111'; $.ajax( { type: "POST", url: "ReportList.aspx/GetReportsSentWithinDates", data: '{"searchInput": "' + searchInput + '"}', contentType: "application/json; charset=utf-8", dataType: "json", context: receivedContext, //CONTEXT success: displayResultForLog } ); }
目前我正在使用以下内容。 任何改进建议?
function displayResultForLog(result) { if (result.hasOwnProperty("d")) { result = result.d } if (result !== undefined && result != null ) { if (result.hasOwnProperty('length')) { if (result.length >= 1) { for (i = 0; i < result.length; i++) { var sentDate = result[i]; } } else { $(requiredTable).append('Length is 0'); } } else { $(requiredTable).append('Length is not available.'); } } else { $(requiredTable).append('Result is null.'); } }
未定义的引用在这里是JavaScript undefined属性
undefined属性表示尚未为变量赋值。
代替
if($.isEmptyObject(result))
将
if(typeof result !== 'undefined' && result.length < 1)
工作?
未定义的引用在这里是JavaScript undefined属性
undefined属性表示尚未为变量赋值。