加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ajax数据类型分析

发布时间:2020-12-16 01:53:29 所属栏目:百科 来源:网络整理
导读:ajax在浏览器和服务器端传输数据的本质是文本内容(不支持二进制数据),这些文本内容可以是json、xml、html或者纯文本格式,浏览器端把服务端返回的文本内容转为JavaScript的json对象、xml对象或者html对象。目前主流的JavaScript库都提供了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直接在浏览器输入,即可看到返回的文本数据,如图所示。


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对象。



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对象。



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);
});






服务端

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,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();
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读