I confronted a situation where I need to read an XML file located in the server and display XML data back in HTML using JavaScript. And the solution should be working with modern and old browsers. So I thought of sharing the code snippet.
The requirement is simple. Read and XML file and Display data in HTML.
Let's go...
We are going to create only 3 files place them in the same folder. "EmployeeData.xml", EmployeeView.html" and "ReadEmployee.js"
Here is a sample XML file which we are going to read.
Now Let's write the HTML, again its so simple. I have used some simple CSS styles to make the view looks better.
First take a look at the JavaScript file.
Let's try to understand the code.
Here we use XMLHttpRequest which is used to pass data between server and client.
It should work like a charm. Good Luck Dev Folks!
The requirement is simple. Read and XML file and Display data in HTML.
Let's go...
We are going to create only 3 files place them in the same folder. "EmployeeData.xml", EmployeeView.html" and "ReadEmployee.js"
Here is a sample XML file which we are going to read.
Now Let's write the HTML, again its so simple. I have used some simple CSS styles to make the view looks better.
First take a look at the JavaScript file.
Let's try to understand the code.
Here we use XMLHttpRequest which is used to pass data between server and client.
- Check if the browser supports the XMLHttpRequest object. If yes, create an XMLHttpRequest.
- If the browser doesn't support XMLHttpRequest then create an ActiveXObject.
- Send the request to the sever using xmlhttp.open("GET","EmployeeData.xml",true); and xmlhttp.send();
- Here we are using open(method,url,async). method: either GET or POST, url:url of the file to open, async: set it to true or false. When using async = true, specify a function to execute when the response is ready in the onreadystatechange event. Read more about onreadystatechange. Setting the value async = false doesn't require further actions.
- send() method sends the request to the server.
- Get the response XML from the server and manipulate as shown in the latter part of the code.
It should work like a charm. Good Luck Dev Folks!
No comments:
Post a Comment