下载  >  开发技术  >  其它  > Ajax\XML and JSON for Ajax

Ajax\XML and JSON for Ajax 评分:

Ajax\XML and JSON for Ajax
CHAPTER 4 XML and jSoN for Ajax Do you really need XML for an Ajax application? The previous chapter showed that you don t always need XML. In particular, if you only have one data point, XML is overkill. But the fact is, most web applications deal with multiple data points: user names,passwords, addresses, cities, states, zip codes, etc. How will you decipher those fields when they're sent back from the server? In some cases, passing a string of delimited values may seem like the simplest g XMl has advan For one thing, XML is self-de During debugging, you can look at the XMI string and see exactly what goes where; that is a luxury you wont have with a string of comma-separated values Another reason for using XML is that an XML parser is built into most browsers The parsing work has already been done for you; all you have to do is leverage the built-in parser. Sure, you could pass the data in other formats-Java properties files comma or tab-separated values, yAML files, or a cute custom format that you've designed yourself--but then you would have to write your own parser in JavaScript There is another good way to send data to and from the server: Java a: Script Object Notation (SON). We will discuss JSON toward the end ns of this chapter. The character decoder The example in this chapter is similar to the one in the previous chapter, but instead of the server returning one data point, it's going to return five. Retuning a small col lection of data shows what happens when you go beyond a single data point and illustrates why most Ajax applications need XMl or some other way to structure the data that is passed from the server to the client. Figure 4-1 shows how the user interface of the application will look when were done. The design is simple enough: we send a character to the server using XmLhtTprEquest(), and the server responds with a String containing the five conver sions in XMl format (decimal, octal, hexadecimal, binary, and HTML). The callback()function in the client then calls a function to parse the XMl and popu- late the fields in the b aJAjax On Java, Chapter 4 Example-Microsoft Internet Explorer Fie Edt View Favorites Tools Help Address s h icho4-CharacterDecodt AJAX CHARACTER DECODER Press a key to find its value. Enter key Hi Key Pressed Decimal HeX彐decm Octal HTML Figure 4-1. The complete ajax Character decoder example Now it starts to get fun. One keystroke fills in all the data fields, and although it doesnt look like much is going on from the user's perspective, from the program mer's perspective we know that the application is communicating with the server without a clunky submit or reload or any waiting for the page to refresh Setting Up a Simple XML Document Before we delve into the code, we need to make some decisions. We're going to return data using XML, but how should that XMl be structured? What should our XML response look like? We dont want anything complex, so we'll aim to create an XML document that looks like this <converted-values> <decimal>97/decimal> <hexadecimal,0x61</hexadecimal> <hyper>&amp; OX61; </hyper> binary>1100001B</b Inar> /converted-values> With this format, the browser can use its document object model (dom)parser to ndex and retrieve the data 20 Chapter 4: XML and JSoN for Ajax There are many ways to create this XMl document. For the sake of simplicity, we'll first use a StringBuffer to wrap the data with xml tags later we'll look at other ways to create the xml document c When I talk about XML formatting, I'm referring to the server wrap ping the data in XML. The client receives the XML-formatted string in ; the httPreSpoNse and parses it for the individual data fields The client passes data through the request using either HttPpoSt()or hTtpgEt() There is no reason for the client to send xml data to the server because the data is already wrapped in the request as name/value Using a Servlet to Build an XML Document Let's start by looking at the servlet code that wraps the data in XML. This servlet is shown in Example 4-1 The Ajax responseservlet Converts a character to hex, decimal, binary, octal, and HTML, then k wraps each of the fields with XML and sends them back through the response package com. AJAXb import java. io IOEXception; import javax. servlet ServletException; importjavax.servlethttpHttpservlet; importjavax.servlethttpHttpservletreqUest; importjavax.servlethttpHttpservletreSponse; public class AjaxresponseServlet extends Httpservlet public void doget(Http Servletrequest reg HttpservletreSponse res throws ServletException, IOException i // key is the parameter passed in from the JavaScript // variable named url (see index htm1) String key =req. getParameter("key") StringBuffer returN if(k nu11){ // extract the first character from ke / as an int, then convert that int to a str int keyInt key charAt(o); returnXML new String Buffer ("\r\n<converted-values>" ); turnXML. append ("\r\n<decimal> Integer toString(keyInt)+</decimal> turn XML append ("\r\n<hexadecimal>0x"+ Integer toString(keyInt, 16)+</hexadecimal>") returnXML. append ("\r\n<octal>o"+ (keyInt, 8)+</octal> Setting Up a Simple XML Document2 Example 4-1. The Ajax ResponseServlet (continued) ppend( \r\n<hyper>damp; OX Integer toString(keyInt, 16)+"</hyper>") returrXML. append("\r\n<binary>+ Integer toString(keyInt, 2)+ B</binary> ) eturnXML. append ("\r\n</converted-values"); he response res. setContentTy res setHeader ("Cache-Control","no-cache ) / write out the XML string res.getWriter(). write(returnXML toString ( )) else / if key comes back as a null, return a question mark res setContentType ("text/xnl IessetHeader ("Cache-Control","nO-Cache") res. getWriter().write("? ) This code is similar to the code from Chapter 3 The only thing that has been added is the code to wrap the data with Xml tags returnXML new StringBuffer("\r\n<converted-values> returnXML, append ("\r\n<decimal>+ Integer toString(keyInt)+"</decimal>") returnXML, append ("\r\n<hexadecimal>0x"+ Integer toString(keyInt, 16)+"</hexadecimal>") returnXML. append ("\r\n<octal>o"+ Integer toString(key Int, 8)+</octal>"); returnXML. append("ir\nchyper>&amp; OX"+ Integer tostring(keyInt, 16)+";</hyper> ) returnXML. append ("\r\binary"+ Integer toString(keyInt, 2)+"B</binary>"); returnXML, append ("\r\n</coniverted-values>") This code simply sets up a StringBuffer called returnXML. We then convert the incoming value to decimal, hex, etc. wrap it with an appropriate XML tag; and append it to the buffer. When we've finished all five conversions and added the clos ing tag (</ converted-values>), we send the response back to the ajax client using res.getWriter().write(). We return a question mark (without any XMl wrapping) if the key we received was null Other Ways to build the xml document Building an XMl document by appending to a StringBuffer is a common approach but it's far from ideal, particularly if you need to generate a large document program- matically. Fortunately, there are alternatives 22 Chapter 4: XML and JSON for Ajax JDOM One option is to use the jDOM library to write the XML. download the jdom. jar file fromhttp:/www.jdom.organdputitinyourapplicationsWeb-inF/liBdirectory Then, instead of writing to a String Buffer, use JDOM to build the XMl, as shown in Example 4-2 xample 4-2. Using DOM to create the XMl document / additional imports needed for JDOM import org. jdom. Document import org. jdom Element import org. jdom output. XMLOutputter; public String create]domXML(int key) throwS IOException Document document new Document o; // create root node t= new org.jdom Element( document set Root E lement(root) / create your node org. jdom Element element new org. jdon Element("decimal") / add content to the node element. addContent(Integer toString(key)) / add your node to root root. add Content(element element= new org. jdom Element("hexadecimal") element. addContent( Integer toString(key, 16)) element. addcontent ("0"+ Integer to String(key, 8)) root. addContent(element); element Org·jdon element. addCoritent("&ox"+ Integer tostring(key, 16); element new org. jdom Element("binary " ) element. addContent(Integer tostring(key, 2)+"B") root. add Content(element); // output JDOM document as a String of bytes XMLOutputter outputter= new XMLOutputter(); return outputter. outputString( document) In the preceding code, we first create a Document (org. jdom. Document), then an Element named root with the String"converted-values"as its value. That element becomes the root of the xml document here's what the document looks like at this <converted-values> Setting Up a Simple XML Document23 To add child elements to the root we create new elements and add them to the root element. The code that creates the decimal element and adds it to the root element looks like this org. jdam. E lement element new org. jdom Element ("decimal"); element. add Content(integer tostring(key) root. addContent(element) We repeat this process until we 've added all the elements to the root then we use an XMLOutputter to format the document into a String that we can send back to the cl ent. The jDOM XMl document now looks like this(with lineleeds and spaces added for readabili o"encoding="UTF-8 <converted-values> <decimaly97</decimal> <hexadecimal l>0x61</hexadecimal> tal>0141</octal <binary>1100001B</binary> </converted-values> dom4j dom4j is an XMl library similar in intent to JDOM. After downloading dom 4j from http://www.dom4j.org/download.htmlandinstallingitinyourapplicationsWeb INF/Lib directory, you can use it to create your XML document. As shown in Example 4-3, we create a document, add a root element to the document, add the elements and data to the root, and then return the document in a String Example 4-3. Using dom4j to create the XMl document // additional imports for dom4j t org. dom4j Document ort org. dom4j. DocumentHelper; import org.dom4j Document Exception Imao rt org. dom4j Element; import org. dom4]. io OutputFormat import org. dom4j io XMLWriter; public String createDom4jXML(int key) throws IOException t Documentdocument- DocumentHelper createDocument (; Element root =document. addElement("converted-values"); Element element root addElement ("decimal").addText nteger tostring(key)) element root addElement ("hexadecimal").addText( Ox"+ Integer toString(key, 16)) element root addElement("octal" ). addText("O"+ Integer tostring(key, 8)); element root addElement("hyper"). addText("&Ox"+ Integer tostring(key, 16)) 24 Chapter 4: XML and JSoN for Ajax Example 4-3. Using dom4j to create the XMl document(continued) element root addElement ("binary").addText(Integer toString(key, 2)+"B") StringBuffer xmldoc null Stringwriter sw new StringWriter() OutputFormat outformat= OutputFormat create Prettyprint (; XMLWriter writer- new XMLWriter(sW, out format); citer write document) writer. close() xmlDoc= SW. getBuffer (; return xmlDoc. toString (); The dom4j library uses the static method DocumentHelper createDocument()to cre ate the XMl document. The method root. addElement()puts a child element on the root element, and addText()puts the data in the elements. The OutputFormat class then used to format the Xmldocument. so the document looks like this. ncoding=UTF-8 <converted-values> <decimal>97</de <hexadecimal>0x61</hexadecimal> hyper> &amp; 0x61</h <binary>1100001B</binary> </converted-values> This step can be skipped, because it only formats the document for readability by adding linefeeds and spaces. Since humans shouldn't need to read this document (unless you are debugging), you wont need the formatting To use dom4 without the formatting, simply replace these two lines outputFormat outformat= outputFormat. createPrettyPrint() XMLWriter writer= new XMLWriter (sw, outformat ) with this line XMLWriter writer new XMLWriter(sw); SAX SAX, the Simple aPI for XML, provides another way to create an XML document for an Ajax application. It may be faster than JDOM or dom 4J, because it doesn't require building a DOM tree for your document. Start by initializing a StringWriter and a streamResult initialize the streamResult with the streamWriter then get a SAXTransformerFactory and get a TransformerHandler trom that. The Trans formerHandler allows you to create an XMI document by starting a docu ment and appending elements and data to the TransformerHandler. Example 4-4 shows how it works Setting Up a Simple XML Document25

...展开详情
2012-02-09 上传 大小:2.28MB
举报 收藏
分享
Ajax\XML and JSON for Ajax

Ajax\XML and JSON for Ajax

立即下载
Ajax 解析XML+json总结

Ajax 解析XML+json总结,很好的资源哦。欢迎大家来下载。

立即下载
AJAX and JSON with jQuery

AJAX and JSON with jQuery http://chyu.scripts.mit.edu/ajax-json-jquery-examples.zip

立即下载
Ajax技术结合XML或JSON的使用比较

Ajax,用于描述WEB应用程序风格和创建高度交互的WEB应用所需的一组技术。运用Ajax技术,在XML、JSON中选择满足应用程序需求和功能、节省存储空间、易于生成和解析的数据格式成为WEB应用程序设计的关键。该文通过XML、JSON的介绍、实例运用及重要特征与环境支持区别的分析得出JSON是适用于Ajax web应用程序的理想数据交换格式的结论。

立即下载
Saving ASP.Net Form Data with jQuery AJAX and JSON Parser

Saving ASP.Net Form Data with jQuery AJAX and JSON Parser

立即下载
ajax跨域 返回json

实现jquery ajax跨域。前台页面 和 java代码类

立即下载
基于ASP.NET+XML +JSON实现的Ajax 异步数据操作程序源码例子

基于ASP.NET+XML +JSON实现的Ajax 异步数据操作程序源码例子。

立即下载
ajax例子,json例子

ajax json 不刷新 。。。。。。。。。。。。

立即下载
AJAX_11JSON详解

JSON详解JSON详解JSON详解JSON详解JSON详解JSON详解JSON详解

立即下载
Ajax 中对Json 使用

Ajax 对Josn 的使用,了解什么是Json 方便开发,方便操作,感谢使用

立即下载
ajax原理、JSON介绍

主要关于ajax原理、XMLHTTPRequest等介绍

立即下载
使用Ajax动态加载JSON文件

使用Ajax动态加载JSON文件的实例源码

立即下载
ajax对象及json应用

本人刚从达内毕业,以上代码是学习中老师详细讲解的.含有很清楚的注释.ajax对象的获取以及使用,包括jQuery对ajax对象的封装都有详细的代码.供大家参考学习

立即下载
ajax分页,json数据返回

jquery ajax请求,json返回数据到前台,无刷新的分页.

立即下载
Ajax中使用JSON.doc

Ajax中使用JSON的实际案例,通过此案例可实际制作出符合要求的开发环境

立即下载
jquery ajax Datatable与json之间数据转换

jquery ajax Datatable与json之间数据转换jquery ajax Datatable与json之间数据转换jquery ajax Datatable与json之间数据转换jquery ajax Datatable与json之间数据转换jquery ajax Datatable与json之间数据转换jquery ajax Datatable与json之间数据转换jquery ajax Datatable与json之间数据转换jquery ajax Datatable与json之间数据转换

立即下载
jquery xml转json插件

jquery的一个插件,可将xml格式内容转为json格式内容。支持ajax异步。该插件值得拥有. JS中有开源官方地址,可查看demo

立即下载
前台ajax与后台json传递

解决从前台到后台数据传输的详细代码及注释

立即下载
ajax例子+json.jar包

ajax,我坐的一个小例子截图和gson架包,有问题期望与你交流。

立即下载
VS2008基于ajax异步操作 json (附源码)

VS2008基于ajax异步操作 json (附源码)VS2008基于ajax异步操作 json (附源码)VS2008基于ajax异步操作 json (附源码)VS2008基于ajax异步操作 json (附源码)

立即下载