ajax數據類型分析

ajax在瀏覽器和服務器端傳輸數據的本質是文本內容(不支持二進制數據),這些文本內容可以是json、xml、html或者純文本格式,瀏覽器端把服務端返回的文本內容轉爲JavaScript的json對象、xml對象或者html對象。目前主流的JavaScript庫都提供了ajax請求的封裝,以jQuery爲例。

$.ajax({
    url: 'http://請求路徑',
    data: {},               // 請求參數,沒有可以不寫
    dataType: 'json',       //支持json、xml、html、text、jsonp等
    type: 'get',            //有get和post兩種請求,默認是get
    timeout: 60000          //ajax請求超時
}).done(function(data){
    //ajax請求成功回調函數
}).fail(function(){
    //ajax請求失敗回調函數
});

jQuery通過dataType把返回的數據轉成相應的JavaScript對象,因此我們在使用過程中無需手動進行轉換,只要在回調函數中使用即可。如果把ajax請求的路徑以及參數通過url直接在瀏覽器輸入,即可看到返回的文本數據,如圖所示。


ajax

json

目前絕大部分的ajax請求的數據都是json格式,在某種程度上ajax基本上和json綁定在一起使用,以至於給人一種錯覺就是ajax就是處理json數據。其實json只是一種數據格式,跟ajax並沒有必然的聯繫,json數據需要在JavaScript中轉換成對象實例(目前大部分瀏覽器都內置了JSON.parse()方法,也可以用jQuery的$.parseJSON()方法)。

下面用$.ajax()請求json數據,由於jQuery自動把數據轉成json對象,因此把dataType指定爲text。

$.ajax({
    url: 'http://localhost:8280/logweb/test/json.do',
    dataType: 'text'
}).done(function(text){
    console.dir(arguments);
    //text的類型
    console.dir('text的類型是:' + Object.prototype.toString.call(text));
    console.dir(text);

    var json = $.parseJSON(text);
    console.dir('json的類型是:' + Object.prototype.toString.call(json));
    console.dir(json);
});

從瀏覽器控制檯輸出的結果可知,text是字符串,json是Object對象。

json

xml

ajax也可以處理xml數據,確切的說是JavaScript也能處理xml數據。下面用$.ajax()請求xml數據,由於jQuery自動把數據轉成xml對象,因此把dataType指定爲text。

$.ajax({
    url: 'http://localhost:8280/logweb/test/xml.do',
    dataType: 'text'
}).done(function(text){
    console.dir(arguments);
    //text的類型
    console.dir('text的類型是:' + Object.prototype.toString.call(text));
    console.dir(text);

    var xml = $.parseXML(text);
    console.dir('xml的類型是:' + Object.prototype.toString.call(xml));
    console.dir(xml);
});

從瀏覽器控制檯輸出的結果可知,text是字符串,xml是XMLDocument對象。

xml

html

ajax也可以接收html,通常html都是直接插入其他html元素中。

$.ajax({
    url: 'http://localhost:8280/logweb/test/html.do',
    dataType: 'text'
}).done(function(text){
    console.dir(arguments);
    //text的類型
    console.dir('text的類型是:' + Object.prototype.toString.call(text));
    console.dir(text);

    var html = $.parseHTML(text);
    console.dir(html);

    //把html附加到body
    $(document.body).append(html);
});


自定義數據格式

json、xml和html都是標準格式,也可以自定義格式。下面返回用(,)分隔的自定義數據格式,相對於json等標準格式,自定義格式不易被理解。

$.ajax({
    url: 'http://localhost:8280/logweb/test/custom.do',
    dataType: 'text'
}).done(function(text){
    console.dir(arguments);
    //text的類型
    console.dir('text的類型是:' + Object.prototype.toString.call(text));
    console.dir(text);

    var data = {}, items = text.split(',');
    $.each(items, function(i, v){
        var parts = v.split('_');
        data[parts[0]] = parts[1];
    });

    console.dir(data);
});

自定義

jsonp

jsonp並不屬於ajax,jsonp和ajax實現的原理不一樣,jsonp的出現只是爲了彌補ajax不能跨域請求的缺點(ajax不能跨域請求是瀏覽器做的限制)。雖然jsonp不屬於ajax,jQuery爲了方便還是把jsonp放在ajax方法裏調用,把dataType設置爲jsonp即可。

$.ajax({
    url: 'http://localhost:8280/logweb/test/jsonp.do',
    dataType: 'jsonp'
}).done(function(data){
    console.dir('data的類型是:' + Object.prototype.toString.call(data));
    console.dir(data);
});

jsonp


jsonp

服務端

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSON;

@Controller
@RequestMapping("/test")
public class TestController {

    /**
     * 返回json
     * 
     * @param response
     */
    @RequestMapping("/json.do")
    public void json(HttpServletResponse response) {
        response.setContentType("text/plain;charset=utf-8");
        response.setCharacterEncoding("utf-8");

        // 構造json
        Map<String, Object> json = new HashMap<String, Object>();
        json.put("date", new Date());
        json.put("name", "小明");
        json.put("age", 18);

        try {
            // 這裏用FastJSON生成JSON字符串
            response.getWriter().write(JSON.toJSONString(json));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回xml
     * @param response
     */
    @RequestMapping("/xml.do")
    public void xml(HttpServletResponse response) {
        response.setContentType("text/plain;charset=utf-8");
        response.setCharacterEncoding("utf-8");

        //用Dom4j構造xml
        Document doc = DocumentHelper.createDocument();
        Element root = doc.addElement("root");
        root.addElement("date").setText(new Date().getTime() + "");;
        root.addElement("name").setText("小明");
        root.addElement("age").setText("18");

        try {
            response.getWriter().write(doc.asXML());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 返回html
     * @param response
     */
    @RequestMapping("/html.do")
    public void html(HttpServletResponse response) {
        response.setContentType("text/plain;charset=utf-8");
        response.setCharacterEncoding("utf-8");

        String html = "<div>" + new Date().toString() + "</div><div>姓名:小明</div><div>年齡:18歲</div>";

        try {
            response.getWriter().write(html);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 自定義格式
     * @param response
     */
    @RequestMapping("/custom.do")
    public void custom(HttpServletResponse response) {
        response.setContentType("text/plain;charset=utf-8");
        response.setCharacterEncoding("utf-8");

        String str = "date_" + new Date().toString() + "," + "name_小明,age_18";

        try {
            response.getWriter().write(str);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * jsonp數據
     * @param callback jsonp的回調函數名稱
     * @param response
     */
    @RequestMapping("/jsonp.do")
    public void jsonp(String callback, HttpServletResponse response) {
        response.setContentType("text/plain;charset=utf-8");
        response.setCharacterEncoding("utf-8");

        // 構造json
        Map<String, Object> json = new HashMap<String, Object>();
        json.put("date", new Date());
        json.put("name", "小明");
        json.put("age", 18);

        //拼接jsonp
        StringBuilder str = new StringBuilder();
        str.append(callback);
        str.append("(");
        str.append(JSON.toJSONString(json));
        str.append(");");

        try {
            response.getWriter().write(str.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章