1. 程式人生 > 實用技巧 >Json,Ajax,i18n 國際化

Json,Ajax,i18n 國際化

1、什麼是 JSON?

JSON (JavaScript Object Notation) 是一種輕量級的資料交換格式。易於人閱讀和編寫。同時也易於機器解析和生成。JSON
採用完全獨立於語言的文字格式,而且很多語言都提供了對 json 的支援(包括 C, C++, C#, Java, JavaScript, Perl, Python
等)。 這樣就使得 JSON 成為理想的資料交換格式。
json 是一種輕量級的資料交換格式。
輕量級指的是跟 xml 做比較。
資料交換指的是客戶端和伺服器之間業務資料的傳遞格式。

1.1、JSON 在 JavaScript 中的使用。

1.1.1、json 的定義

json 是由鍵值對組成,並且由花括號(大括號)包圍。每個鍵由引號引起來,鍵和值之間使用冒號進行分隔,多組鍵值對之間進行逗號進行分隔。
json 定義示例:

var jsonObj = {
"key1":12,
"key2":"abc",
"key3":true,
"key4":[11,"arr",false],
"key5":{
"key5_1" : 551,
"key5_2" : "key5_2_value"
},
"key6":[{
"key6_1_1":6611,
"key6_1_2":"key6_1_2_value"
},{
"key6_2_1":6621,
"key6_2_2":"key6_2_2_value"
}]
};

1.1.2、json 的訪問

json 本身是一個物件。
json 中的 key 我們可以理解為是物件中的一個屬性。
json 中的 key 訪問就跟訪問物件的屬性一樣: json 物件.key
json 訪問示例:
alert(typeof(jsonObj));// object json 就是一個物件
alert(jsonObj.key1); //12
alert(jsonObj.key2); // abc
alert(jsonObj.key3); // true
alert(jsonObj.key4);// 得到陣列[11,"arr",false]
// json 中 陣列值的遍歷
for(var i = 0; i < jsonObj.key4.length; i++) {
alert(jsonObj.key4[i]);
}
alert(jsonObj.key5.key5_1);//551
alert(jsonObj.key5.key5_2);//key5_2_value
alert( jsonObj.key6 );// 得到 json 陣列
// 取出來每一個元素都是 json 物件
var jsonItem = jsonObj.key6[0];
// alert( jsonItem.key6_1_1 ); //6611
alert( jsonItem.key6_1_2 ); //key6_1_2_value

json 的兩個常用方法

json 的存在有兩種形式。
一種是:物件的形式存在,我們叫它 json 物件。
一種是:字串的形式存在,我們叫它 json 字串。
一般我們要操作 json 中的資料的時候,需要 json 物件的格式。
一般我們要在客戶端和伺服器之間進行資料交換的時候,使用 json 字串。
JSON.stringify() 把 json 物件轉換成為 json 字串
JSON.parse() 把 json 字串轉換成為 json 物件
示例程式碼:

// 把 json 物件轉換成為 json 字串
var jsonObjString = JSON.stringify(jsonObj); // 特別像 Java 中物件的 toString
alert(jsonObjString)
// 把 json 字串。轉換成為 json 物件
var jsonObj2 = JSON.parse(jsonObjString);
alert(jsonObj2.key1);// 12
alert(jsonObj2.key2);// abc

JSON 在 java 中的使用

1.2.1、javaBean 和 json 的互轉

@Test
public void test1(){
Person person = new Person(1,"國哥好帥!");
// 建立 Gson 物件例項
Gson gson = new Gson();
// toJson 方法可以把 java 物件轉換成為 json 字串
String personJsonString = gson.toJson(person);
System.out.println(personJsonString);
// fromJson 把 json 字串轉換回 Java 物件
// 第一個引數是 json 字串
// 第二個引數是轉換回去的 Java 物件型別
Person person1 = gson.fromJson(personJsonString, Person.class);
System.out.println(person1);
}

1.2.2、List 和 json 的互轉

// 1.2.2、List 和 json 的互轉
@Test
public void test2() {
List<Person> personList = new ArrayList<>();
personList.add(new Person(1, "國哥"));
personList.add(new Person(2, "康師傅"));
Gson gson = new Gson();
// 把 List 轉換為 json 字串
String personListJsonString = gson.toJson(personList);
System.out.println(personListJsonString);
List<Person> list = gson.fromJson(personListJsonString, new PersonListType().getType());
System.out.println(list);
Person person = list.get(0);
System.out.println(person);
}

1.2.3、map 和 json 的互轉
// 1.2.3、map 和 json 的互轉

@Test
public void test3(){
Map<Integer,Person> personMap = new HashMap<>();
personMap.put(1, new Person(1, "國哥好帥"));
personMap.put(2, new Person(2, "康師傅也好帥"));
Gson gson = new Gson();
// 把 map 集合轉換成為 json 字串
String personMapJsonString = gson.toJson(personMap);
System.out.println(personMapJsonString);
// Map<Integer,Person> personMap2 = gson.fromJson(personMapJsonString, new
PersonMapType().getType());
Map<Integer,Person> personMap2 = gson.fromJson(personMapJsonString, new
TypeToken<HashMap<Integer,Person>>(){}.getType());
System.out.println(personMap2);
Person p = personMap2.get(1);
System.out.println(p);
}

AJAX 請求

2.1、什麼是 AJAX 請求

AJAX 即“Asynchronous Javascript And XML”(非同步 JavaScript 和 XML),是指一種建立互動式網頁應用的網頁開發技術。
ajax 是一種瀏覽器通過 js 非同步發起請求,區域性更新頁面的技術。
Ajax 請求的區域性更新,瀏覽器位址列不會發生變化
區域性更新不會捨棄原來頁面的內容

2.2、原生 AJAX 請求的示例:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="pragma" content="no-cache" />
<meta http-equiv="cache-control" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
// 在這裡使用 javaScript 語言發起 Ajax 請求,訪問伺服器 AjaxServlet 中 javaScriptAjax
function ajaxRequest() {
// 1、我們首先要建立 XMLHttpRequest
var xmlhttprequest = new XMLHttpRequest();
// 2、呼叫 open 方法設定請求引數
xmlhttprequest.open("GET","http://localhost:8080/16_json_ajax_i18n/ajaxServlet?action=javaScriptAj
ax",true)
// 4、在 send 方法前繫結 onreadystatechange 事件,處理請求完成後的操作。
xmlhttprequest.onreadystatechange = function(){
if (xmlhttprequest.readyState == 4 && xmlhttprequest.status == 200) {
var jsonObj = JSON.parse(xmlhttprequest.responseText);
// 把響應的資料顯示在頁面上
document.getElementById("div01").innerHTML = "編號:" + jsonObj.id + " , 姓名:" +
jsonObj.name;
}
}
// 3、呼叫 send 方法傳送請求
xmlhttprequest.send();
}
</script>
</head>
<body>
<button onclick="ajaxRequest()">ajax request</button>
<div id="div01">
</div>
</body>
</html>

2.3、jQuery 中的 AJAX 請求

$.ajax 方法
url 表示請求的地址
type 表示請求的型別 GET 或 POST 請求
data 表示傳送給伺服器的資料
格式有兩種:
一:name=value&name=value
二:{key:value}
success 請求成功,響應的回撥函式
dataType 響應的資料型別
常用的資料型別有:
text 表示純文字
xml 表示 xml 資料
json 表示 json 物件

$("#ajaxBtn").click(function(){
$.ajax({
url:"http://localhost:8080/16_json_ajax_i18n/ajaxServlet",
// data:"action=jQueryAjax",
data:{action:"jQueryAjax"},
type:"GET",
success:function (data) {
// alert("伺服器返回的資料是:" + data);
// var jsonObj = JSON.parse(data);
$("#msg").html("編號:" + data.id + " , 姓名:" + data.name);
},
dataType : "json"
});
});

$.get 方法和$.post 方法
url 請求的 url 地址
data 傳送的資料
callback 成功的回撥函式
type 返回的資料型別

// ajax--get 請求
$("#getBtn").click(function(){
$.get("http://localhost:8080/16_json_ajax_i18n/ajaxServlet","action=jQueryGet",function (data) {
$("#msg").html(" get 編號:" + data.id + " , 姓名:" + data.name);
},"json");
});
// ajax--post 請求
$("#postBtn").click(function(){
$.post("http://localhost:8080/16_json_ajax_i18n/ajaxServlet","action=jQueryPost",function (data)
{
$("#msg").html(" post 編號:" + data.id + " , 姓名:" + data.name);
},"json");
});

$.getJSON 方法
url 請求的 url 地址
data 傳送給伺服器的資料
callback 成功的回撥函式

// ajax--getJson 請求
$("#getJSONBtn").click(function(){
$.getJSON("http://localhost:8080/16_json_ajax_i18n/ajaxServlet","action=jQueryGetJSON",function
(data) {
$("#msg").html(" getJSON 編號:" + data.id + " , 姓名:" + data.name);
});
});

表單序列化 serialize()
serialize()可以把表單中所有表單項的內容都獲取到,並以 name=value&name=value 的形式進行拼接。

// ajax 請求
$("#submit").click(function(){
// 把引數序列化
$.getJSON("http://localhost:8080/16_json_ajax_i18n/ajaxServlet","action=jQuerySerialize&" +
$("#form01").serialize(),function (data) {
$("#msg").html(" Serialize 編號:" + data.id + " , 姓名:" + data.name);
});
});

應用

使用 AJAX 驗證使用者名稱是否可用

UserServlet 程式中 ajaxExistsUsername 方法:

protected void ajaxExistsUsername(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
// 獲取請求的引數 username
String username = req.getParameter("username");
// 呼叫 userService.existsUsername();
boolean existsUsername = userService.existsUsername(username);
// 把返回的結果封裝成為 map 物件
Map<String,Object> resultMap = new HashMap<>();
resultMap.put("existsUsername",existsUsername);
Gson gson = new Gson();
String json = gson.toJson(resultMap);
resp.getWriter().write(json);
}

regist.jsp 頁面中的程式碼:

$("#username").blur(function () {
//1 獲取使用者名稱
var username = this.value;
$.getJSON("http://localhost:8080/book/userServlet","action=ajaxExistsUsername&username=" +
username,function (data) {
if (data.existsUsername) {
$("span.errorMsg").text("使用者名稱已存在!");
} else {
$("span.errorMsg").text("使用者名稱可用!");
}
});
});

使用 AJAX 修改把商品新增到購物車

CartServlet 程式:

protected void ajaxAddItem(HttpServletRequest req, HttpServletResponse resp) throws ServletException,
IOException {
// 獲取請求的引數 商品編號
int id = WebUtils.parseInt(req.getParameter("id"), 0);
// 呼叫 bookService.queryBookById(id):Book 得到圖書的資訊
Book book = bookService.queryBookById(id);
// 把圖書資訊,轉換成為 CartItem 商品項
CartItem cartItem = new CartItem(book.getId(),book.getName(),1,book.getPrice(),book.getPrice());
// 呼叫 Cart.addItem(CartItem);新增商品項
Cart cart = (Cart) req.getSession().getAttribute("cart");
if (cart == null) {
cart = new Cart();
req.getSession().setAttribute("cart",cart);
}
cart.addItem(cartItem);
System.out.println(cart);
// 最後一個新增的商品名稱
req.getSession().setAttribute("lastName", cartItem.getName());
//6、返回購物車總的商品數量和最後一個新增的商品名稱
Map<String,Object> resultMap = new HashMap<String,Object>();
resultMap.put("totalCount", cart.getTotalCount());
resultMap.put("lastName",cartItem.getName());
Gson gson = new Gson();
String resultMapJsonString = gson.toJson(resultMap);
resp.getWriter().write(resultMapJsonString);
}

pages/client/index.jsp 頁面

html 程式碼:

<```
div style="text-align: center">
<c:if test="${empty sessionScope.cart.items}">
<%--購物車為空的輸出--%>

當前購物車為空 <%--購物車非空的輸出--%> 您的購物車中有 ${sessionScope.cart.totalCount} 件商品 您剛剛將${sessionScope.lastName}加入到了購 物車中 ```

javaScript 程式碼:

<Script type="text/javascript">
$(function () {
// 給加入購物車按鈕繫結單擊事件
$("button.addToCart").click(function () {
/**
* 在事件響應的 function 函式 中,有一個 this 物件,這個 this 物件,是當前正在響應事件的 dom 物件
* @type {jQuery}
*/
var bookId = $(this).attr("bookId");
// location.href = "http://localhost:8080/book/cartServlet?action=addItem&id=" + bookId;
// 發 ajax 請求,新增商品到購物車
$.getJSON("http://localhost:8080/book/cartServlet","action=ajaxAddItem&id=" +
bookId,function (data) {
$("#cartTotalCount").text("您的購物車中有 " + data.totalCount + " 件商品");
$("#cartLastName").text(data.lastName);
})
});
});
</Script>

i18n 國際化(瞭解內容)

什麼是 i18n 國際化?

  • 國際化(Internationalization)指的是同一個網站可以支援多種不同的語言,以方便不同國家,不同語種的使用者訪問。
  • 關於國際化我們想到的最簡單的方案就是為不同的國家建立不同的網站,比如蘋果公司,他的英文官網是: http://www.apple.com 而中國官網是 http://www.apple.com/cn
  • 蘋果公司這種方案並不適合全部公司,而我們希望相同的一個網站,而不同人訪問的時候可以根據使用者所在的區域顯示不同的語言文字,而網站的佈局樣式等不發生改變。
  • 於是就有了我們說的國際化,國際化總的來說就是同一個網站不同國家的人來訪問可以顯示出不同的語言。但實際上這種需求並不強烈,一般真的有國際化需求的公司,主流採用的依然是蘋果公司的那種方案,為不同的國家建立不同的頁 面。所以國際化的內容我們瞭解一下即可。
  • 國際化的英文 Internationalization,但是由於拼寫過長,老外想了一個簡單的寫法叫做 I18N,代表的是 Internationalization 這個單詞,以 I 開頭,以 N 結尾,而中間是 18 個字母,所以簡寫為 I18N。以後我們說 I18N 和國際化是一個意思。

國際化相關要素介紹