2012-05-07 109 views
0

我是新來的AJAX世界,所以請原諒我的n00bishness。我有一個XML文件,它看起來像這樣:我有一個加載的一切,但在頁面載入成分的XSL文件,但我想要實現的是,在點擊(鏈接或按鈕,我不AJAX將XML加載圖像

<juices> 
<smoothie id="SY4301"> 
    <name>Strawberry Yumghurt</name> 
    <price currency="GBP"> 
     <perunit type="wholesale">1.23</perunit> 
     <perunit type="RRP">1.89</perunit> 
     <percrate>28.50</percrate> 
    </price> 
    <description>Velvety yoghurt smoothie made with fresh strawberry and rasperries.</description> 
    <ingredients> 
     <ingredient image="/images/strawberry.jpg" quantity="9">Strawberries</ingredient> 
     <ingredient image="/images/Raspberry.jpg" quantity="4">Raspberries</ingredient> 
     <ingredient image="/images/yoghurt.jpg"quantity="200ml">Greek Yoghurt</ingredient> 
     <ingredient image="/images/honey.jpg" quantity="30ml">Runny Honey</ingredient> 
     <ingredient image="/images/milk.jpg"quantity="40ml">Semi-skimmed Milk</ingredient> 
    </ingredients> 
    <nutrition per="100ml"> 
     <kcal unit="cal">140</kcal> 
     <kjoules unit="KJ">442</kjoules> 
     <carbohydrate unit="g">27.9</carbohydrate> 
     <protein unit="g">1.4</protein> 
     <fat unit="g">8.4</fat> 
     <fibre unit="g">2.8</fibre> 
    </nutrition> 
    <imageloc>http://www5.bbk.ac.uk/~akaufm01/jvfma/Images/Products/morning_kick.jpg</imageloc> 
</smoothie> 
</juices> 

不要介意哪一個),將一個div(#description)的內容替換爲其圖像所伴隨的成分列表,其位置將存儲在image屬性中。

我看了一些教程,建議使用jQuery來實現這一目標,但我沒有太多的運氣讓這個工作。我知道我也可以在JS中使用XMLHttpRequest函數,但不確定哪種方法更好。

任何意見將不勝感激!

感謝, 安迪

回答

0

那麼首先你需要了解什麼是你用AJAX做,因爲有不同的方法進行調用的jQuery的AJAX技術,讓我們使用的基本屬性

//Handle the ajax in the event click of your button with ID MyButton 
$('#MyButton').click(function(){ 
    $.ajax({ 
     type: "Type of your http Request could be GEt or Post", 
     url: " the url where you obtain that xml", 
     data: "ïf you need to pass some data to the url" 
     dataType: "in your case should be XML which is the data type that you're going to handle in the success function", 
     success: function(data){ 
      //parse your xml which it contains in the var data 
      //You could set the data parse in your div with a append or html method 
     }'define a function or put a function already defined', 
     error: 'define a function in case of error' 
    }); 
}); 

Here's the doc about an ajax in jquery

Here's you can find the documentation of the method about

And here how you can parse an xml using jquery

+0

'$( '#爲myButton')點擊(函數(){$ 阿賈克斯({ 類型: 「GET」, 網址: 「smoothies.xml」, 數據類型: 「XML」, 成功:function(data){(xml).find('node')。each(function(){} {var(title)$(this).find('ingredient')。text(); $('#Description')。append($(this).find('name')。text()); }'定義函數或放置已定義的函數', 錯誤:alert('Error'); }); });' –

+0

我已經添加了這個jQuery,但它沒有做任何事情。有任何想法嗎? –

+0

我是我的代碼我只有一個存根,你不能複製和粘貼,它會工作。在成功方法之後刪除註釋 – Jorge