jquery and XML
Fast and strong traversal system, gorgeous selector syntax, this may be the reason why jquery is so popular. Of course, it also has detailed documentation. It's mostly used to deal with HTML, but here you'll see how to apply it to XML.
Using jquery for DOM element manipulation and traversal
Before you can use it, identify the jquery library that you reference on the page. Then simply use jquery () or its simplified form $ () to pass a selector as its first parameter. A selector is typically a string that specifies one or more elements. Listing 20 shows the use of some basic jquery selectors.
Listing 20. Basic JQuery Selectors
<script type= "Text/javascript" > var allimages = $ ("img"); All IMG elements var Allphotos = $ ("Img.photo"); All IMG elements with class "photo" var Curphoto = $ ("Img#currentphoto"); IMG element with id "Currentphoto" </script> |
One thing to keep in mind is that the jquery method returned is always a jquery object. This type of object supports chained operations (see listing 21). This feature is also common in other JavaScript frameworks.
Listing 21. Basic JQuery operation with chained method calls
<script type= "Text/javascript" > $ ("img"). CSS ({"padding": "1px", "Border": "1px solid #333"}) . Wrap ("<div class= ' Img-wrap '/>"); </script> |
The code above selects all the IMG elements in the page and sets padding and border, then wraps all the img with a div with Img-wrap class.
Listing 22 shows how jquery simplifies an example of the previous section.
Listing 22. Creating and injecting a DOM node with JQuery
<script type= "Text/javascript" > Alert ($ ("H1:first"). html ()); . Text () also works and might is better suited here $ ("#auth"). Text ("Sign Out"); var $li = $ ("<li>list Item text</li>"); $ is used as VAR prefix to indicate JQuery object $ ("Ul#nav"). Append ($li); </script> |
Working with XML using jquery
It was previously mentioned that the first parameter passed to jquery $ () is a string-type selector. The second obscure parameter allows you to set the context, start a jquery node, or use the currently selected element as a root node. The default jquery will use document as the current context, but it is better to specify the context in more detail and specific to a particular element. When you do XML processing, you need to set the context to the root node of the XML (see Listing 23).
Listing 23. Retrieving values from a XML document with JQuery
<script type= "Text/javascript" > Get value of single node (with JQuery) var description = $ ("description", XmlData). text (); XmlData was defined in previous section Get values of nodes from a set (with JQuery) var Relateditems = $ ("Related_item", xmlData); var relateditemvals = []; $.each (Relateditems, function (i, CurItem) { Relateditemvals.push (Curitem.text ()); }); </script> |
The above code makes the representation quite concise. By passing the node name to jquery and setting its context to XMLData, you can easily get the node you want. Get the value of the element, just need a turn.
Because innerHTML does not work with non-HTML elements, it is not possible to use the jquery HTML () method to get the value of a node. Although JQuery provides a cross-browser approach to innertext to get the value of an element, there are still some differences between browsers when it comes to working with XML. For example, IE will ignore the nodes containing null values (spaces, tab characters, line breaks), and when dealing with such cases, Firefox will treat these nodes as normal nodes. To avoid this inconsistency, you can create a function to handle. Some jquery functions are required in this function: Contents (), filter (), and trim ().
Listing 24. Cross-browser JavaScript functions for accurate text value retrieval of a node
<script type= "Text/javascript" > /** * Retrieves non-empty text nodes which is children of passed XML node. * Ignores child nodes and comments. Strings which contain only blank spaces * or only newline characters is ignored as well. * @param node {object} XML DOM Object * @return JQuery Collection of text nodes */ function gettextnodes (node) { return $ (node). Contents (). filter (function () { Return ( Text node, or CDATA node (this.nodename== "#text" && this.nodetype== "3") || this.nodetype== "4") && And not empty ($.trim (This.nodeValue.replace ("\ n", ""))!== "") ); }); } /** * Retrieves (text) node value * @param node {Object} * @return {String} */ function Getnodevalue (node) { var textnodes = gettextnodes (node); var TextValue = (node && isnodecomment (node))? Isnodecomment is defined above Node.nodevalue: (Textnodes[0])? $.trim (textnodes[0].textcontent): ""; return TextValue; } </script> |
Now look at how to set the value of the node (see listing 25). There are two points to note in the sample code: first, setting the text value of the root result overrides all child nodes. In addition, if there is no value before a node, then use node["Textcontent" instead of node.textcontent. Because there is no textcontent attribute at all in IE hollow node.
Listing 25. Cross-browser JavaScript function for accurate setting of the text value of a node
<script type= "Text/javascript" > function setNodeValue (node, value) { var textnodes = gettextnodes (node); if (textnodes.get (0)) { Textnodes.get (0). NodeValue = value; } else { node["textcontent"] = value; } } </script> |
Dom Properties and jquery
In some previous examples, it has been shown that even using the most primitive JavaScript to handle attributes in the DOM is very straightforward. In the same way, jquery offers a corresponding simplification. More importantly, attributes can be used in selectors, very powerful.
Listing 26. Getting and setting DOM element attributes with JQuery
<script type= "Text/javascript" > var item = $ ("item[content_id= ' 1 ']", xmlData); Select item node with CONTENT_ID attribute set to 1 var pubDate = item.attr ("date_published"); Get Value of date_published attribute Item.attr ("Archive", "true"); Set new attribute called Archive, with value set to True </script> |
As you can see from the code, the attr () method of jquery can set settings or return property values. What is more powerful is that jquery allows properties to be provided in the selector to return a specific element. As shown in the code above, we get the element with content_id 1.
To load XML with jquery's Ajax
Perhaps you already know that Ajax is a web technology that uses JavaScript to get XML asynchronously from the server. Ajax itself is dependent on the API provided by XMLHttpRequest (XHR) to send requests to the server and get the response from the server. In addition to providing a powerful way to traverse and manipulate DOM elements, jquery provides cross-browser Ajax support. That is to say, to get XML from Ajax is simply to call Ajax's Get method. Listing 27 shows an example of this.
Listing 27. Loading an external XML file with JQuery ' s Ajax method
<script type= "Text/javascript" > $.ajax ({ Type: "GET", URL: "/path/to/data.xml", DataType: "xml", Success:function (XmlData) { var totalnodes = $ (' * ', xmlData). length; Count XML Nodes Alert ("This XML file has" + totalnodes); }, Error:function () { Alert ("Could not retrieve XML file."); } }); </script> |
The $.ajax () method has a rich set of options and can be invoked through a few other simplified variants, such as $.getscript () importing JavaScript scripts and executing them, $.getjson () The JSON data is obtained and can then be used in the success callback. When loading an XML file, you need to know the basic syntax of Ajax. As shown in the code above, we set the type Get,url to get the XML file from the "/path/to/data.xml" path, and then also indicate that the file type is XML. When data is obtained from the server, a method in success or error is triggered. In this example, if the load succeeds, a pop-up window displays the number of all nodes. The asterisk selector for jquery indicates that all elements are matched. The most important point is that in the callback function, the first parameter is used to receive the data returned from the server. The name of this parameter is random, and the next context is set to the returned data.
There are cross-domain issues to be aware of when dealing with Ajax-related requests, and it is generally not possible to get files from different domains for security reasons. So the code in the above example may be different in your actual program.
Work with external XHTML like XML
Because XHTML is a subset of XML, it is absolutely no problem to process XHTML like XML. The fact that you have a need to deal with XHTML is another matter, but the truth is that you can do it. For example, it is possible to import an XHTML page and then parse the data from it, although I would suggest a more robust approach.
Although the traversal and processing of DOM elements has been described before, jquery can also be used to process XML, although it is necessary to load the XML file into the code first. The content of this section contains different methods and basic examples for completing XML processing.
Dealing with xml--jquery and XML with jquery