2015-06-22 43 views
0

我試圖加載一些json到jQuery tmpl中。jQuery getJSON數據不加載到tmpl

的頁面是在這裏:http://stefairclough.com/jsontest/

$(document).ready(function() { 

    $.getJSON("http://stefairclough.com/jsontest/json.json", 
      function(data){ 
       $("#news_articles").empty(); 
       $("#news_template").tmpl(data).appendTo("#news_articles"); 
      }) 
      .error(function(xhr) { 
        console.log(xhr) 
      });    
}); 

的JSON是在http://stefairclough.com/jsontest/json.js

我似乎無法弄清楚,爲什麼它不會工作。

+0

請出示相關的代碼片段 – Moak

回答

0

似乎你的XHR請求失敗。嘗試爲您的JSON文件提供JSON標頭。嘗試重命名文件:

http://stefairclough.com/jsontest/json.json

+0

嗨亨利,感謝您的建議,但我重命名的文件,它仍然沒有爲我工作。 –

+0

這個問題不是關於jQuery模板,而是關於你的GetJSON。文件http://stefairclough.com/jsontest/json.js確實會返回一個json字符串,但不會返回一個json頭文件。所以jQuery調用將不會接受它。 –

+0

我不知道你是否生成了json.js,或者它是否是一個靜態文件,由服務器得到,但是在那裏出了問題。 –

0

您的JSON並不似乎是有效的JSON。

請嘗試使用棉絨您的JSON如下:http://pro.jsonlint.com/

+0

感謝您的幫助! JSON無效 –

1

您的JSON測試文件的末尾有;刪除

[ 
    {"Headline": "Headline Test 1", "Url": "http://stefairclough.com"}, 
    {"Headline": "Headline Test 2", "Url": "http://stefairclough.com"}, 
    {"Headline": "Headline Test 3", "Url": "http://stefairclough.com"} 
]; <--- here 
+0

確定已修復它謝謝! –

1

只是把上面的腳本模板

1.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> 
<script src="jquery.tmpl.js"></script> 

2.

<script id="news_template" type="text/x-jquery-tmpl"> 
     <div class="news_item"> 
      <h3>${Headline}</h3> 
      <p>Source: <a href="${Url}" target="_blank">${Url}</a> 
     </div> 
    </script> 
  • 您的JS文件然後

    $(文件)。就緒(函數(){

    $.getJSON("http://stefairclough.com/jsontest/json.js", 
          function(data){ 
           $("#news_articles").empty(); 
           $("#news_template").tmpl(data).appendTo("#news_articles"); 
          }) 
          .error(function(xhr) { 
            console.log(xhr) 
          });    
    }); 
    </script> 
    
  • +1

    感謝您的幫助,我現在有腳本工作,json無效。 –