2013-03-06 30 views
1
獲取數據時,遇到了「不確定」與其他數據

我從JSON使用jQuery使用此代碼獲取值:在出發從JSON

$(document).ready(function() { 
      $.ajax({ 
       type : 'GET', 
       url : 'outfitters.json', 
       dataType : 'json', 
       success : processTeam, 
       error : function() { 
        alert('error'); 
       } 
      }); 
     }); 

     function processTeam(data) { 
      var company = data.company; 
      $("h1").html(company); 

      var locations; 
      for (i = 0; i < data.locations.length; i++) { 

       locations += data.locations[i].name + "<br/>"; 

      } 
      $("li").html(locations); 

     } 

事實上,我得到預期的輸出,但有一個額外的「不確定」輸出是這樣的:

undefinedKincardine 
Killarney 
Bon Echo 

此外,我使用jQuery Mobile的列表框中,但儘管它是爲了顯示它在三個不同的人其只在一個列表框填充值。

<ul data-role="listview"> 
      <li> 

      </li> 

     </ul> 

我在我的代碼中做的任何錯誤?

+0

是什麼'data.locations'看起來像? – Blender 2013-03-06 04:51:47

回答

1

初始化您的變量var locations = '';

+0

如何將它附加到li時發生的錯誤? – user1890338 2013-03-06 04:53:32

+0

@ user1890338所以你有多個'li's,只有一個數據被附加到它? – Musa 2013-03-06 04:58:01

+0

是這樣的問題。 – user1890338 2013-03-06 05:00:43

1

你需要先初始化變量。

var locations=''; 

因爲當你試圖追加未初始化的數據。所以首先它將是undefined + youvalue。所以你得到undefinedKincardine的第一個結果

1

沒有初始化的位置,你使用它,因此它通過未定義的錯誤消息。

var locations = ''; 
0

我假設你的HTML是看起來如下

<div data-role="page"> 
    <div data-role="header"> 
     <h1>header</h1> 
    </div> 
    <div data-role="content"> 
     <h2 id="companyName">my list</h2> 
     <div id="locationList"></div> 
    </div> 
</div> 

那麼你processTeam應儘可能遵循

var company = JSON.parse(data); 

//setting company name 
$('#companyName').text(company.company); 

//setting the list view 
//running a loop first 
var locationsStr = "<ul data-role='listview'>"; 
$.each(company.locations, function(){ 
    locationsStr = locationsStr + "<li><a href='#'>"+this.name+"</a></li>"; 
}); 
locationsStr = locationsStr+ "</ul>"; 
$('#locationList').html(locationsStr); 
$('#locationList ul').listview(); 

你可以看看這裏的工作小提琴http://jsfiddle.net/eTpSQ/1/