In this post, find out jQuery code on how to parse JSON, parse XML and parse HTML. If you are still using custom code for parsing any of these and making your life more miserable then stop doing it. Why? If you are not aware then here is a news for you that jQuery has inbuilt utility methods for each. Which are,
Related Post:
Using parseJSON()
This method takes a well-formed JSON string and returns the resulting JavaScript object. It is available from jQuery 1.4.1 version.
This method parses a string into an XML document. $.parseXML uses the native parsing function of the browser to create a valid XML Document. It is available from jQuery 1.5 version.
This method parses a string into an array of DOM nodes. $.parseHTML uses a native DOM element creation function to convert the string to a set of DOM elements, which can then be inserted into the document. This method was added in jQuery version 1.8
- parseJSON()
- parseXML()
- parseHTML()
Related Post:
Using parseJSON()
This method takes a well-formed JSON string and returns the resulting JavaScript object. It is available from jQuery 1.4.1 version.
$(document).ready(function() {
var jsonp = '[{"Name":"Abc"},{"Name":"Xyz"}]';
var sName = '';
var obj = $.parseJSON(jsonp);
$.each(obj, function() {
sName += this['Name'] + "<br/>";
});
$('span').html(sName);
});
Live Demo
Using parseXML()This method parses a string into an XML document. $.parseXML uses the native parsing function of the browser to create a valid XML Document. It is available from jQuery 1.5 version.
$(document).ready(function() {
var str= '<xml version='1.0'><name>jQuery By Example</name></xml>';
var xmlDoc = $.parseXML(str);
var $xml = $(xmlDoc);
var $Name = $xml.find('name');
$('span').html($Name);
});
Live Demo
Using parseHTML()This method parses a string into an array of DOM nodes. $.parseHTML uses a native DOM element creation function to convert the string to a set of DOM elements, which can then be inserted into the document. This method was added in jQuery version 1.8
$(document).ready(function () {
var str = "Hello, <b>my blog name is</b> jQueryByExample."
var sName = '';
var sHTML = $.parseHTML(str);
$.each(sHTML, function (i, el) {
sName += el.nodeName + "<br/>";
//el.nodeName = #text otherwise HTML tag name.
//el.nodeValue = actual value of the node.
});
$('span').html(sName);
});
Live Demo
Feel free to contact me for any help related to jQuery, I will gladly help you.
No comments:
Post a Comment