2012-12-03 86 views
1

我有以下jQuery Ajax場景,其中webmethod返回字符串的集合。數組結果的jQuery Ajax回調

  1. 集合可以是空
  2. 集合可以爲非空,但是零個記錄。
  3. 收集具有一個或多個記錄

下面的代碼工作正常。它使用jQuery.isEmptyObject。當它不是Plain Object時,建議不要使用isEmptyObject()

如何在不使用isEmptyObject()的情況下處理結果?

注意:ajax「結果」是「不明顯」。

參考:

  1. Is object empty?
  2. Javascript's hasOwnProperty() Method Is More Consistent Than The IN Operator

CODE

//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 

     } 
     ); 
} 

回答

0

目前我正在使用以下內容。任何改進建議?

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 Property

未定義屬性指示的變量沒有被分配的值。

0

而不是

if($.isEmptyObject(result)) 

if(typeof result !== 'undefined' && result.length < 1) 

工作?

參考未定義的是這裏JavaScript undefined Property

的未定義的屬性指示變量尚未賦值。

+0

否....如果結果爲空,則會在檢查結果中出錯。長度 – Lijo

+1

好點,我已經通過建議修改了檢查對象是否未定義。 – daveyfaherty

+1

它是'!==「undefined」'或'!== undefined'? – Lijo