Replace item prices in HTML tags from JSON data

久未见 提交于 2019-12-07 19:36:50

问题


I have a very simple problem, but I just can't figure it out. My Javascript knowledge is a bit rusty :-)

Here is my JSON data (stored in a file prices.xml)

{
"prices": {
"bananas": "2,39",
"apples": "3,39"
}
}

Here is my html:

<ul>
<LI>Our price for bananas:<SPAN id="bananaprice">BANANA PRICE SHOULD GO HERE</SPAN></LI>
<LI>Our price for apples:<SPAN id="appleprice">APPLE PRICE SHOULD GO HERE</SPAN></LI>
</ul>

All i really need is a javascript (no jquery if possible) that pulls the values from the prices.xml and replaces the SPAN values. I do not need a "hyper flexible" script that does loops and all that. It has to be super simple.

Thank you very much in advance


回答1:


Assuming you're using jQuery for the AJAX request.

$.ajax({
    url: yourURL
    dataType: 'json',
    success: function( data )
    {
        var prices = data.prices;

        $('#bananaprice').text( prices.bananas );
        $('#appleprice').text( prices.apples );
    }
});

If you aren't using jQuery or AJAX then you'd need to assign a variable to the object to reference them.

var items = {
    "prices" : {
        "bananas" : "$X.XX",
        "apples" : "$X.XX"
    }
};

var banana = document.getElementById('bananaprice'),
    apple = document.getElementById('appleprice')
    price = items.prices;

banana.innerHTML = price.bananas;
apple.innerHTML = price.apples;



回答2:


you should also rename the prices.xml to prices.json and check that your webserver will put the correct mime type on the file. This not strictly necessary, but in a year when the next guy comes to look over this code they'll wonder why an xml file had json in it.




回答3:


Use a JSON library, or use eval as your data seems safe,See it work here: http://jsfiddle.net/m6qW7/2/

var myPrices = '{ "prices": { "bananas": "2,39","apples": "3,39" }}';
 // string data you got as json

 // added "s" to your span ids for consistency
 var myPricesObj = eval( "(" + myPrices + ")" );
 var prices = myPricesObj["prices"];
 for(fruit in prices)
     document.getElementById(fruit + "price").innerHTML = prices[fruit];


来源:https://stackoverflow.com/questions/5194268/replace-item-prices-in-html-tags-from-json-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!