2012-09-28 40 views
1

爲什麼我越來越typeError值爲null,但在我的螢火蟲我可以說,有價值,而不是空,什麼是問題?爲什麼我越來越typeError值爲空,但在我的螢火蟲,我可以看到有值和不空?

這裏是我的Ajax代碼:

$.ajax({ 
    url: 'get-products.php', 
    type: 'post', 
    datatype: 'json', 
    data: { category: $('.category').val().trim(), keyword: $('.keyword').val().trim() }, 
    success: function(data){ 
     var toAppend = ''; 
     toAppend += '<thead><th>Product Name</th><th>Image</th><th>Price</th><th>Weight</th><th>ASIN</th><th>Category</th></thead>'; 
     if(typeof data === "object"){ 
      for(var i=0;i<data.length;i++){ 
       toAppend += '<tr><td>'+ 
       data[i]['product_name'][0]+'</td><td><img src="'+ 
       data[i]['image'][0]+'" alt=""></td><td>'+ 
       data[i]['price'][0]+'</td><td>'+        
       data[i]['weight']+'</td><td>'+          
       data[i]['asin'][0]+'</td><td>'+           
       data[i]['category'][0]+'</td></tr>'; 
      } 
      $('.data-results').append(toAppend); 
     } 
    } 
}); 

這裏是我的PHP代碼,我知道這是工作:

foreach($xml->Items->Item as $item){ 
$items_from_amazon[] = array(
     'asin'=>$item->ASIN, 
     'product_name'=>$item->ItemAttributes->Title, 
     'image'=>$item->SmallImage->URL, 
     'price'=>$item->ItemAttributes->ListPrice->FormattedPrice, 
     'category'=>$item->ItemAttributes->ProductGroup, 
     'weight' => (string) $item->ItemAttributes->PackageDimensions->Weight.' lbs'); 
} 
echo json_encode($items_from_amazon); 
?> 

下面是從我的螢火蟲結果:

enter image description here

這裏的我的樣品輸出,即使仍然存在,我仍然可以顯示結果像在圖像空的結果,如果圖像爲null,則沒有圖像顯示

enter image description here

+1

看到螢火蟲第七元素,圖像爲null有 – GBD

+0

_Sidenote_你已經錯過了一個'+'>'數據[I] [ '重量'] + '​​'' – undefined

+0

@undefined,那裏是我真正的代碼+ ,我的錯誤soryy –

回答

3

在它看起來像它說的圖像是第7個指標在零Firebug的圖像。 所以,如果你做data.image [index]你正在訪問一個無效的內存位置。圖像屬性必須指向某個東西。

   for(var i=0;i<data.length;i++){ 
//You can save default image in a global variable, hidden div... it is up to you. 
       var img ; 
       if(data[i]['image'] === null){ 
        img = defaultImage ; 
       } 
       else 
       { 
        img = data[i]['image'][0]; 
       } 
       toAppend += '<tr><td>'+ 
       data[i]['product_name'][0]+'</td><td><img src="'+ 
       img +'" alt=""></td><td>'+ //use img here 
       data[i]['price'][0]+'</td><td>'+        
       data[i]['weight']+'</td><td>'+          
       data[i]['asin'][0]+'</td><td>'+           
       data[i]['category'][0]+'</td></tr>'; 
      } 

您希望得到的想法。

+0

我該如何顯示結果? –

+0

我會調試你的服務器端代碼,看看爲什麼元素缺少圖像。您提供的代碼中沒有太多信息。 –

+0

實際上我使用AWS API從AMazon獲取數據,並且我無法阻止某些數據爲空,CAn我仍然顯示結果? –

相關問題