JavaScript

How to Fetch and Display XML Data Using jQuery’s $.get() Method

In this article, we’ll explore how to fetch and display XML data using jQuery’s $.get() method.

Using $.get() to Load XML Data

We will load the XML file from the following link: data.xml.

<!--?xml version="1.0" encoding="utf-8"?-->
<categories>
<item>
<category>TOP</category>
<url>https://dad-union.com/</url>
</item>
<item>
<category>ABOUT</category>
<url>https://dad-union.com/about</url>
</item>
<item>
<category>JAVASCRIPT</category>
<url>https://dad-union.com/category/javascript</url>
</item>
<item>
<category>JQUERY</category>
<url>https://dad-union.com/category/jquery</url>
</item>
</categories>

CSS Example for Displaying XML Data

Below is a CSS example for a button (#btn) that uses $.get() to fetch XML data. Feel free to modify it as needed.

<style type="text/css"> 
#btn{
	width:150px;
	height:30px;
	margin:0 auto;
	background-color:#333;
	color:#FFF;
	font-weight:bold;
	border:solid 1px #333333;
	text-align:center;
	line-height:1.8em;
	cursor:pointer;
}
#btn:hover{
	background-color:#FFF;
	color:#333;
	font-weight:bold;
	border:solid 1px #333333;
}
#cat{
	width:600px;
	margin:0 auto;
	line-height:1.8em;
	padding-top:20px;
}
</style>

JavaScript Example for Fetching and Displaying XML Data

The following script will fetch XML data from the “data.xml” file and display it in the output area (id=”cat”) when the button with id=”btn” is clicked.

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
	$("#btn").one('click', function() {
		$.get("data.xml",function(xml) {
			$(xml).find('item').each(function() {
				$("#cat").append(
					'<div>'
					+ $(this).children('category').text() + ' ⇒ '
					+ '<a href="' + $(this).children('url').text() + '" title="' + $(this).children('category').text() + '">' + $(this).children('url').text() + '</a>'
					+ '</div>'
				);
			});
		});
	});
});
</script>

HTML Example for Displaying XML Data

When the button with id=”btn” is clicked, the fetched XML data will be displayed in the tag with id=”cat”.

<div class="clWrap">

<div id="btn">Click Here</div>

<div id="cat"></div>

</div>

<!--/clWrap-->

Demo Page for Fetching and Displaying XML Data with jQuery’s $.get()

Demo for fetching and displaying XML data with jQuery’s $.get()

There are various other methods for fetching XML data, aren’t there?

※ Use at your own risk. Please do not reuse the Google Analytics tag inside the demo page tags.