package com.demo.json;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.json.simple.JSONValue;
public class JsonTest
{
public static void main(String[] args)
{
// -----------------------------------------------------------------------------
// Object 2 JSON
List<Peoper> peopers = new ArrayList<Peoper>();
Peoper p1 = new Peoper("001", "Taki", "中國");
Peoper p2 = new Peoper("002", "DSM", "China");
peopers.add(p1);
peopers.add(p2);
String result = JsonTool.getJsonString("Peopers", peopers);
System.out.println("JSON: " + result);
// 解析PHP json_encode 字符串
String jsonStr = "{\"Name\":\"\u5e0c\u4e9a\",\"Age\":20}";
Object obj = JSONValue.parse(jsonStr);
System.out.println(obj);
System.out.println();
// -----------------------------------------------------------------------------
// JSON 2 Object
String jsonString = "["
+ "{\"author\":\"7\",\"id\":358,\"title\":\"Japan\",\"pictures\":[{\"description\":\"001\",\"imgPath\":\"/cms/u/cms/www/201203/05150720ii68.jpg\"},{\"description\":\"002\",\"imgPath\":\"/cms/u/cms/www/201203/05150720ii67.jpg\"}],\"path\":\"ip\"},"
+ "{\"author\":\"8\",\"id\":359,\"title\":\"China\",\"pictures\":[{\"description\":\"101\",\"imgPath\":\"/cms/u/cms/www/201203/111111111111.jpg\"},{\"description\":\"102\",\"imgPath\":\"/cms/u/cms/www/201203/222222222222.jpg\"}],\"path\":\"ip\"}]";
JSONArray array = JSONArray.fromObject(jsonString);
// Content.class包含pictures.class,需要設置這個參數
Map<String, Class<pictures>> classMap = new HashMap<String, Class<pictures>>();
classMap.put("pictures", pictures.class);
Object[] objs = new Object[array.size()];
for (int i = 0; i < array.size(); i++)
{
JSONObject jsonObject = array.getJSONObject(i);
objs[i] = (Content) JSONObject.toBean(jsonObject, Content.class, classMap);
}
// 轉換Content,循環輸出所有content
for (int i = 0; i < objs.length; i++)
{
Content content = (Content) objs[i];
System.out.println("author:" + content.getAuthor() + " ID:"
+ content.getId() + " Title:" + content.getTitle() + " Path:" + content.getPath());
// 轉換pictures,循環輸出所有picture
List<pictures> pictures = content.getPictures();
for (int n = 0; n < pictures.size(); n++)
System.out.println("description:"
+ pictures.get(n).getDescription() + " imgPath:" + pictures.get(n).getImgPath());
}
}
}
package com.demo.json;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sf.json.JSONObject;
public class JsonTool
{
public static String getJsonString(Object key, Object value)
{
//System.out.println("key: " + key);
//System.out.println("value: " + value.toString());
JSONObject obj = new JSONObject();
obj.put(key, value); //添加物件
return obj.toString(); //轉換為字符串并返回
}
//解析PHP json_encode 字符串
public static String unescapeUnicode(String str)
{
StringBuffer b=new StringBuffer();
Matcher m = Pattern.compile("\\\\u([0-9a-fA-F]{4})").matcher(str);
while(m.find())
{
b.append((char)Integer.parseInt(m.group(1),16));
}
return b.toString();
}
}
package com.demo.json;
public class People
{
public People()
{
}
public People(String id, String name, String address)
{
this.id = id;
this.name = name;
this.address = address;
}
private String id;
private String name;
private String address;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String toString()
{
return "ID:" + this.id + " Name:" + this.name + " Address:" + this.address;
}
}
package com.demo.json;
import java.util.List;
public class Content {
private String author;
private String id;
private String title;
private List<pictures> pictures;
private String path;
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public List<pictures> getPictures() {
return pictures;
}
public void setPictures(List<pictures> pictures) {
this.pictures = pictures;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
}
package com.demo.json;
public class pictures {
private String description;
private String imgPath;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImgPath() {
return imgPath;
}
public void setImgPath(String imgPath) {
this.imgPath = imgPath;
}
}
使用jQuery進行DOM元素的操作和遍歷
首先確定妳在頁面引用的jQuery庫,才能使用它。然后簡單地使用jQuery()或者它的簡化形式$(), 傳遞一個選擇器作為它的第一個參數。選擇器通常是一個指定了一個或多個元素的字符串。清單20展示了一些基本的jQuery選擇器的使用。
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> |
需要記住的一點是jQuery方法返回的始終是一個jQuery對象。這種對象支持鏈式操作(見清單21)。這一特性在其他JavaScript框架中也是通用的。
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> |
上述代碼選中頁面中所有img元素并設置padding和border, 然后用一個帶img-wrap class 的div 來包裹所有這些img.
清單22則展示了jQuery 是如何將前面章節的一個例子進行簡化。
Listing 22. Creating and injecting a DOM node with jQuery
<script type="text/javascript"> alert($("h1:first").html()); // .text() also works and might be 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> |
使用jQuery 處理XML
之前有提到過傳遞給jQuery $()的第一個參數是一個字符串形式的選擇器。第二個不起眼的參數則允許你設置context,或者開始一個jQuery節點,抑或把當前選擇的元素當作 一個根節點來使用。默認jQuery會把Document作為當前的Context, 但更好的做法是把context指定得更詳細更一些,具體到某個特定的元素身上。在進行XML處理時,需要把context設置為XML的根節點(見清單 23)。
Listing 23. Retrieving values from an 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> |
上述代碼使表示變得相當簡潔。通過向jQuery傳遞節點名稱和設置它的context為xmlData,可以很方便地獲取想要的節點。取得元素的值,剛需要一翻周折了。
因為innerHTML 對 于非HTML元素不管用,所以就不能使用jQuery的html()方法來獲取節點的值。jQuery 雖然提供了一個跨瀏覽器的方法innerText 來獲取元素的值,但當用來處理XML時在瀏覽器間仍有些差異。比如IE會把包含空值(空格,Tab點位 符,換行)的節點給忽略掉,而處理這樣的情況時,FireFox則會把這些節點當作正常節點。為了避免這點不一致性,可以創建一個函數來處理。這個函數里 需要用到一些jQuery函數: contents(), filter() 和 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 are children of passed XML node. * Ignores child nodes and comments. Strings which contain only blank spaces * or only newline characters are 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> |
現在來看看如何設置節點的值(見清單25)。示例代碼中有兩點需要注意:一是設置根結果的文本值會重寫所有子節點。另外就是如果一個節點之前是沒有值的,那么就用 node["textContent"]而不是node.textContent。因為在IE中空節點根本就沒有textContent屬性。
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屬性與jQuery
在之前的一些例子中已經展示了即使用最原始的JavaScript來處理DOM中的屬性也是非常直觀明了的了。同樣地,jQuery也提供了相應的簡化方式。更重要的是,屬性可以用在選擇器中,非常的強大。
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> |
從代碼中可以看出,jQuery的attr()方法即可以設置設置也可以返回屬性值。更強大的是jQuery允許在選擇器中提供屬性來返回特定的元素。下如上面的代碼所展示的那樣,我們獲取到了content_id為1的元素。
通過jQuery的Ajax來裝載XML
或許你已經有所了解,Ajax是用JavaScript來異步從服務器獲取XML的一種Web技術。Ajax本身是依賴XMLHttpRequest (XHR) 所提供的API來向服務器發送請求和從服務器獲取響應的。jQuery除了提供強大的用于遍歷和處理DOM元素的方法外,還提供了跨瀏覽器的Ajax支持。也就是說通過Ajax獲取XML簡單得就是調用Ajax的get方法。清單27展示了這樣的例子。
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> |
$.ajax()方法有一系列豐富的選項設置,并且可以通過其他一些簡化的變形方式來調用,比如$.getScript()會導入JavaScript腳本并執行,$.getJSON()會獲取JSON數據然后可以在Success回調中使用。當裝載XML文件時,妳需要了解一下Ajax的基本語法。如上面代碼所示,我們設置類型為get,url設置為從"/path/to/data.xml"這個路徑獲取XML文件,然后還指明文件類型為XML。當從服務器獲取了數據后,success 或error中的一個方法會被觸發。本例中,裝載成功的話會彈出窗口顯示所有節點數目。jQuery的星號選擇器表示匹配所有元素。最重要的一點是在回調函數中,第一個參數用來接收從服務器返回的數據。這個參數的名字隨便起,接下來的Context就被設置成了這個返回的數據。
在處理Ajax相關的請求時需要注意跨域問題,出于安全性考慮一般不允許從不同的域獲取文件。所以上述例子中的代碼可能在妳實際的程序中有所不同。
像處理XML一樣處理外部的XHTML
因為XHTML是XML的一個子集,所以像XML一樣處理XHTML是完全沒有問題的。至于為什么妳有處理XHTML的需求是另一回事,但事實是妳確實可以這樣做。比如,導入一個XHTML頁面然后從中解析數據是可行的,雖然我會建議用另外更強健的方法來實現。
盡管之前講述了DOM元素的遍歷和處理,jQuery同時也可以用來處理XML,雖然需要先將XML文件破費周折地裝載進代碼中。本節的內容包含了不同的方法和基本的用于完成XML處理的例子。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>省市區三級級聯</title>
<script src="jquery-1.8.0.js"></script>
<script>
var d;
$(document).ready(function (){
$.ajax({
url:"city.xml",
dataType:"xml",
success:function(data){
d = data;
$(data).find("province").each(function (i){
//往province中添加值
$("<option></option>").html($(this).attr("name")).attr("value",$(this).attr("name")).appendTo("#province");
});
chpro($("#province").attr("value")); //選中的值傳給chpro函數
}
});
});
var c;
function chpro(val){
$("#city").empty(); //清空
//遍歷province的name為val下的city
$(d).find("province[name='"+val+"']").find("city").each(function (i){
//往city中添加值 設置屬性value的值為當前對象的屬性name的值
$("<option></option>").html($(this).attr("name")).attr("value",$(this).attr("name")).appendTo("#city");
c = val;
chcity($("#city").attr("value"));
});
}
function chcity(val){
$("#area").empty();
//遍歷province的name為c下的city的name為val下的area
$(d).find("province[name='"+c+"']").find("city[name='"+val+"']").find("area").each(function (i){
$("<option></option>").html($(this).attr("name")).attr("value",$(this).attr("name")).appendTo("#area");
});
}
</script>
</head>
<body>
<form id="myform">
地址:<select id="province" onchange="chpro(this.value)" style="width:150px"></select>
<select id="city" onchange="chcity(this.value)" style="width:150px"></select>
<select id="area" style="width:150px"></select>
</form>
</body>
</html>
文章主要參考于:http://www.ruanyifeng.com/blog/2012/05/responsive_web_design.html(阮一峰的網絡日志)
在這篇文章的基礎上加上了寫自己的理解(文章藍色部分)。
一. 允許網頁寬度自動調整:
"自適應網頁設計"到底是怎么做到的?其實并不難。
首先,在網頁代碼的頭部,加入一行viewport元標簽。
<meta name="viewport" content="width=device-width, initial-scale=1" />
viewport是網頁默認的寬度和高度,上面這行代碼的意思是,網頁寬度默認等于屏幕寬度(width=device-width),原始縮放比例(initial-scale=1)為1.0,即網頁初始大小占屏幕面積的100%。
對于viewport屬性,我是真正在接觸移動web開發是才遇到的,一般的pc布局都是固定的960px,1000px這種。
下面三篇文章是對viewport屬性詳細的解釋:
Viewport(視區概念)——pc端的理解
Viewport(視區概念)——移動端的應用
viewport ——視區概念(轉)
對于老式IE6,7,8瀏覽器需要js處理,由于主要平臺是ios和安卓,所以可以暫時不考慮
二. 不使用絕對寬度
由于網頁會根據屏幕寬度調整布局,所以不能使用絕對寬度的布局,也不能使用具有絕對寬度的元素。這一條非常重要。
具體說,CSS代碼不能指定像素寬度:
width:xxx px;
只能指定百分比寬度:
width: xx%;
或者:
width:auto;
這里開發是指一個網頁不僅能用在pc上,也能同時用于移動端,但是對于webapp這種還是需要單獨做一個webapp使用的頁面。
對于這個知識點,對于我目前做的項目有用處,主要用于控制限定數據庫里讀出來的圖片寬度。
詳見:手機webapp的jquery mobile初次使用心得和解決圖片自適應大小問題
三. 相對大小的字體
字體也不能使用絕對大小(px),而只能使用相對大小(em)。
body {
font: normal 100% Helvetica, Arial, sans-serif;
}
上面的代碼指定,字體大小是頁面默認大小的100%,即16像素。
h1 {
font-size: 1.5em;
}
然后,h1的大小是默認大小的1.5倍,即24像素(24/16=1.5)。
small {
font-size: 0.875em;
}
small元素的大小是默認大小的0.875倍,即14像素(14/16=0.875)。
四. 流動布局(fluid grid)
"流動布局"的含義是,各個區塊的位置都是浮動的,不是固定不變的。
.main {
float: right;
width: 70%;
}
.leftBar {
float: left;
width: 25%;
}
float的好處是,如果寬度太小,放不下兩個元素,后面的元素會自動滾動到前面元素的下方,不會在水平方向overflow(溢出),避免了水平滾動條的出現。
另外,絕對定位(position: absolute)的使用,也要非常小心。
五. "自適應網頁設計"的核心,就是CSS3引入的Media Query模塊。
它的意思就是,自動探測屏幕寬度,然后加載相應的CSS文件。
<link rel="stylesheet" type="text/css"
media="screen and (max-device-width: 400px)"
href="tinyScreen.css" />
上面的代碼意思是,如果屏幕寬度小于400像素(max-device-width: 400px),就加載tinyScreen.css文件。
<link rel="stylesheet" type="text/css"
media="screen and (min-width: 400px) and (max-device-width: 600px)"
href="smallScreen.css" />
如果屏幕寬度在400像素到600像素之間,則加載smallScreen.css文件。
除了用html標簽加載CSS文件,還可以在現有CSS文件中加載。
@import url("tinyScreen.css") screen and (max-device-width: 400px);
六. CSS的@media規則
同一個CSS文件中,也可以根據不同的屏幕分辨率,選擇應用不同的CSS規則。
@media screen and (max-device-width: 400px) {
.column {
float: none;
width:auto;
}
#sidebar {
display:none;
}
}
上面的代碼意思是,如果屏幕寬度小于400像素,則column塊取消浮動(float:none)、寬度自動調節(width:auto),sidebar塊不顯示(display:none)。
這篇文章有詳細的講解:手機web——自適應網頁設計(@media使用)
七. 圖片的自適應(fluid image)
除了布局和文本,"自適應網頁設計"還必須實現圖片的自動縮放。
這只要一行CSS代碼:
img { max-width: 100%;}
這行代碼對于大多數嵌入網頁的視頻也有效,所以可以寫成:
img, object { max-width: 100%;}
老版本的IE不支持max-width,所以只好寫成:
img { width: 100%; }
此外,windows平臺縮放圖片時,可能出現圖像失真現象。這時,可以嘗試使用IE的專有命令:
img { -ms-interpolation-mode: bicubic; }
或者,Ethan Marcotte的imgSizer.js。
addLoadEvent(function() {
var imgs = document.getElementById("content").getElementsByTagName("img");
imgSizer.collate(imgs);
});
不過,有條件的話,最好還是根據不同大小的屏幕,加載不同分辨率的圖片。有很多方法可以做到這一條,服務器端和客戶端都可以實現。
遇到這種問題,請參照這種寫法
s|Application {
fontSize:14;
color:blue;
paddingLeft: 10px;
paddingRight: 10px;
paddingTop: 10px;
paddingBottom: 10px;
horizontalAlign: "left";
}
eclipse版本3.6.2 scala插件url:http://download.scala-ide.org/releases-29/stable/site