2016-09-19 59 views
-2

我對此非常訪問的Json屬性

{"title":"Json 10","body":"lorem","price":"12"} 

的內容是從形式與正在添加以下內容的JSON文件,wehere用戶可以提交該數據。

後來我需要讓用戶能夠在他的網站上顯示這些數據。因此,我正在使用一個小部件。小部件抓住json將內容放入餐廳 - widget-container div

我的問題是:如何訪問每個屬性。有了這個代碼

var jsonp_url = "http://localhost:8000/uploads/json/10_dailydish.json"; 
     jQuery.getJSON(jsonp_url, function(result) { 
     //alert(result.html); 
     $('#restaurant-widget-container').html(result.title); 

     }); 

在我的「餐廳的小部件容器」顯示JSON文件的內容。

我需要在div內顯示標題,正文和價格。但有了上面的代碼,我只是顯示標題。

我也玩過角落找尋與

$('#restaurant-widget-container').append(result.title).append(result.body); 

這基本上工作,但我有一種感覺,有一種更好的方式。

+0

究竟是什麼樣的對象你的餐廳,小工具容器,和你能指望什麼來實現? – lordkain

回答

1

如果你不知道你的JSON對象的按鍵,比你可以用一個簡單的迭代:

for (var k in result) { 
    // This print out the value 
    console.log("The value" + result[k]); 
} 

但是,如果你想直接訪問,如你所知的鑰匙要訪問比,你有2種方法:

var v = result["mykey"]; 

這是很好,如果你有一些配置變量中的字符串鍵。

或者更直接:

var v = result.mykey; 

你問題的第二部分是與訂正使用jquery值的HTML。

下面的代碼:

$('#restaurant-widget-container').append(result.title).append(result.body); 

這只是字符串添加到DOM元素ID爲#餐廳的微件容器

在這裏你應該設計和編寫你的html。你可以直接在你的頁面中做到這一點,然後使用jquery來更新值,或使用模板引擎行句柄。

選擇取決於您的案例和您的口味的複雜性。

所以你可以寫一個簡單的html例子,只需使用jquery和命令式的方法。

// Reset the current content to avoid concatenation 
// of previous results. 
$('#restaurant-widget-container').html(''); 

var $resultTitle = $('<h1></h1>').text(result.title); 

var $resultBody = $('<div></div>').html(result.body); 

var $resultPrice = $('<span></span>').text('Price: ' + result.price + ' $'); 

$('#restaurant-widget-container') 
    .append($resultTitle) 
    .append($resultBody) 
    .append($resultPrice); 

這是一個工作示例。

$(function() { 
 

 
function showResults(result) { 
 
    // Reset the current content to avoid concatenation 
 
    // of previous results. 
 
    $('#restaurant-widget-container').html(''); 
 

 
    var $resultTitle = $('<h1></h1>').text(result.title); 
 

 
    var $resultBody = $('<div></div>').html(result.body); 
 

 
    var $resultPrice = $('<span></span>').text('Price: ' + result.price + ' $'); 
 

 
    $('#restaurant-widget-container') 
 
     .append($resultTitle) 
 
     .append($resultBody) 
 
     .append($resultPrice); 
 
} 
 
    
 
    $('button').click(function(ev) { 
 
    ev.preventDefault(); 
 
    showResults({"title": "My cool title!", "body": "All you need to write goes here...", "price": 123.45}); 
 
    }); 
 
    
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="restaurant-widget-container"> 
 
    </div> 
 
<hr/> 
 
<button>Show</button>

+0

我的鑰匙是「標題」,「身體」和「價格,我需要將它們鏈接到我的餐廳 - 小部件 - 容器分區 – Mamulasa

+0

對不起,我想了一些更多的線索來幫助你。請更新您的問題,並添加更多關於您想要放置哪些vealues的詳細信息,以及爲什麼您不能這樣做。 –

+0

我已更新我的問題 – Mamulasa