2011-12-02 52 views
0

我只需要檢查我的響應對象中是否有一些非零結果,而不必運行循環($ .each或其他)並增加一個計數器(儘管在第一次迭代後我可以中斷計數)。我想我可以使用jQuery的$ .size(),如果有結果並且沒有結果,則返回1和0。我在http://api.jquery.com/size/搜索,但沒有找到確認。有任何想法嗎 ?如何使用jQuery ajax檢查json響應對象中的非零結果?

這裏是我的簡單的代碼 -

  $.ajax({ 
      type: "POST", 
      data: postdata, 
      async: false, 
      url: posturl, 
      dataType: "json", 
      success: function(response) 
      { 
       var results = response.allResults; 
       alert($(results).size()+" and "+results.length); 

       //alerts "0 and 0" - when no results 
       //alerts "1 and undefined" - when there are 1 or more results 

      } 
     }); 

在後端PHP邏輯 -

//some array with key value pairs 
$results = $this->_something($idsArray); 
echo json_encode(array("allResults" => $results)); 

更新
我已經嘗試與length屬性,你可以在我的代碼中看到例如,當存在非零結果時,它會提示undefined

輸出的 console.log(response.allResults);

當有非零結果

-

Object { 109="add_offline_pack_test", 110="add_offline_pack_test1", 111="add_offline_pack_test2", more...} 

當沒有結果 -

[] 
+0

使用'results.length'應該可以。你是否嘗試在控制檯輸出'response'來檢查'response.allResults'等於什麼? – jabclab

+0

我會看看通話返回的原始JSON。從你報告的結果來看,就像'array(「allResults」=> $ results)'返回'nil',而不是空數組,沒有結果,這看起來很奇怪。 –

+0

剛查過日誌,查看我的更新 –

回答

0

嘗試length,而不是大小..

+1

再次看看這個問題:他確實。 –

1

你的問題似乎是,雖然你在想的allResults作爲一個數組,它實際上不是 - 它仍然是一個鍵值對對象 - ,除非它是空的!

發生這種情況是因爲PHP的json_encode只處理數組作爲「真實」數組,如果這些鍵都是整數,並且從零開始連續,或者數組爲空。否則,它將數組視爲鍵值對的關聯數組。

因此,您的測試可以簡單地是長度屬性是否存在?

if (results.length === undefined) { 
    // results is an object of key:value pairs 
} else { 
    // results is an array 
    if (results.length) { 
     throw "expected empty array isn't!"; 
    } 
} 

當你使用jQuery,你也可以使用$.isArray()測試您是否已經收到一個(空的)數組,而不是一個對象。

0

由於$results鍵值對(而不是僅僅值),json_encode將其編碼爲一個對象(因爲對象具有鍵 - 值對)時,你有任何結果的陣列,但空數組時沒有(因爲$results是一個數組)。

所以當沒有結果時,從response.allResults得到的結果是一個空數組(因此其長度爲0)。當有結果時,你得到的結果就是一個包含這些結果的對象。對象沒有長度成員,所以沒有定義。

這樣做$(obj),其中obj是一些物體(未陣列),其結果是這樣的對象:

{ 0: obj, length: 1 } 

這樣做$(arr),其中arr是一些陣列,其結果是一個對象像這樣:

{ length: arr.length, 0: arr[0], 1: arr[1], etc. } 

因爲你的結果是一個空數組當沒有結果,則通過$(result)返回的對象將是這樣的:

{ length: 0 } 

所以如果有效果,$(result)的長度將是1(因爲它被給定的對象),並且如果你沒有結果,這將是0(因爲它被給予一個空數組) 。 $.size只需返回$.length,如鏈接到的文檔頁所述。

0

簡單使用此代碼:

$.ajax({ 
     type: "POST", 
     data: postdata, 
     async: false, 
     url: posturl, 
     dataType: "json", 
    success: function (response) { 
     if (response.d.results == undefined) { 
      //do that 
     } 
     else { 
      //do that 
     } 
    }, 
    error: function (response) { 
     // do that 
    } 
}); 

我希望幫助。使用response.d.results.length您可以從查詢中獲取多個行。