ajax和json

ajax

实现方式:
1. 原生的JS实现方式(了解)
			 //1.创建核心对象
            var xmlhttp;
            if (window.XMLHttpRequest)
            {// code for IE7+, Firefox, Chrome, Opera, Safari
                xmlhttp=new XMLHttpRequest();
            }
            else
            {// code for IE6, IE5
                xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
            }

            //2. 建立连接
            /*
                参数:
                    1. 请求方式:GET、POST
                        * get方式,请求参数在URL后边拼接。send方法为空参
                        * post方式,请求参数在send方法中定义
                    2. 请求的URL:
                    3. 同步或异步请求:true(异步)或 false(同步)
             */
            xmlhttp.open("GET","ajaxServlet?username=tom",true);

            //3.发送请求
            xmlhttp.send();

            //4.接受并处理来自服务器的响应结果
            //获取方式 :xmlhttp.responseText
            //什么时候获取?当服务器响应成功后再获取

            //当xmlhttp对象的就绪状态改变时,触发事件onreadystatechange。
            xmlhttp.onreadystatechange=function()
            {
                //判断readyState就绪状态是否为4,判断status响应状态码是否为200
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                   //获取服务器的响应结果
                    var responseText = xmlhttp.responseText;
                    alert(responseText);
                }
            }


2. JQeury实现方式
	1. $.ajax()
		* 语法:$.ajax({键值对});
		 //使用$.ajax()发送异步请求
            $.ajax({
                url:"ajaxServlet1111" , // 请求路径
                type:"POST" , //请求方式
                //data: "username=jack&age=23",//请求参数
                data:{"username":"jack","age":23},
                success:function (data) {
                    alert(data);
                },//响应成功后的回调函数
                error:function () {
                    alert("出错啦...")
                },//表示如果请求响应出现错误,会执行的回调函数

                dataType:"text"//设置接受到的响应数据的格式
            });
	2. $.get():发送get请求
		* 语法:$.get(url, [data], [callback], [type])
			* 参数:
				* url:请求路径
				* data:请求参数
				* callback:回调函数
				* type:响应结果的类型
							$.get("ajax",{
				                name:"小黄",
				                age:"22"
				            },function (data) {
				                $("#aa").prop("value",data);
				            },"text");
        
	3. $.post():发送post请求
		* 语法:$.post(url, [data], [callback], [type])
			* 参数:
				* url:请求路径
				* data:请求参数
				* callback:回调函数
				* type:响应结果的类型
					
3. Axios实现
	1. get
	// Make a request for a user with a given ID
	axios.get('/user?ID=12345')
	  .then(function (response) {
	    // handle success
	    console.log(response);
	  })
	  .catch(function (error) {
	    // handle error
	    console.log(error);
	  })
	  .finally(function () {
	    // always executed
	  });

	2.post
		axios.post('/user', {
		    firstName: 'Fred',
		    lastName: 'Flintstone'
		  })
		  .then(function (response) {
		    console.log(response);
		  })
		  .catch(function (error) {
		    console.log(error);
		  });
		  
			// Send a POST request
			axios({
			  method: 'post',
			  url: '/user/12345',
			  data: {
			    firstName: 'Fred',
			    lastName: 'Flintstone'
			  }
			});

	3. interceptor请求与响应拦截
	// Add a request interceptor
	axios.interceptors.request.use(function (config) {
	    // Do something before request is sent
	    return config;
	  }, function (error) {
	    // Do something with request error
	    return Promise.reject(error);
	  });
	 
	// Add a response interceptor
	axios.interceptors.response.use(function (response) {
	    // Any status code that lie within the range of 2xx cause this function to trigger
	    // Do something with response data
	    return response;
	  }, function (error) {
	    // Any status codes that falls outside the range of 2xx cause this function to trigger
	    // Do something with response error
	    return Promise.reject(error);
	  });
	  
	4.实例化
	const instance = axios.create({
	  baseURL: 'https://some-domain.com/api/',
	  timeout: 1000,
	  headers: {'X-Custom-Header': 'foobar'}
	});

json

1. JSON转为Java对象
	1. 导入jackson的相关jar包
	2. 创建Jackson核心对象 ObjectMapper
	3. 调用ObjectMapper的相关方法进行转换
		1. readValue(json字符串数据,Class)
2. Java对象转换JSON
	1. 使用步骤:
		1. 导入jackson的相关jar包
		2. 创建Jackson核心对象 ObjectMapper
		3. 调用ObjectMapper的相关方法进行转换
			1. 转换方法:
				* writeValue(参数1,obj):
                    参数1:
                        File:将obj对象转换为JSON字符串,并保存到指定的文件中
                        Writer:将obj对象转换为JSON字符串,并将json数据填充到字符输出流中
                        OutputStream:将obj对象转换为JSON字符串,并将json数据填充到字节输出流中
                * writeValueAsString(obj):将对象转为json字符串

			2. 注解:
				1. @JsonIgnore:排除属性。
				2. @JsonFormat:属性值得格式化
					* @JsonFormat(pattern = "yyyy-MM-dd")

			3. 复杂java对象转换
				1. List:数组
				2. Map:对象格式一致
JsonUtils
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class JsonUtils {

    public static final ObjectMapper mapper = new ObjectMapper();

    private static final Logger logger = LoggerFactory.getLogger(cn.lixiang.common.utils.JsonUtils.class);

    @Nullable
    public static String toString(Object obj) {
        if (obj == null) {
            return null;
        }
        if (obj.getClass() == String.class) {
            return (String) obj;
        }
        try {
            return mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            logger.error("json序列化出错:" + obj, e);
            return null;
        }
    }

    @Nullable
    public static <T> T toBean(String json, Class<T> tClass) {
        try {
            return mapper.readValue(json, tClass);
        } catch (IOException e) {
            logger.error("json解析出错:" + json, e);
            return null;
        }
    }

    @Nullable
    public static <E> List<E> toList(String json, Class<E> eClass) {
        try {
            return mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, eClass));
        } catch (IOException e) {
            logger.error("json解析出错:" + json, e);
            return null;
        }
    }

    @Nullable
    public static <K, V> Map<K, V> toMap(String json, Class<K> kClass, Class<V> vClass) {
        try {
            return mapper.readValue(json, mapper.getTypeFactory().constructMapType(Map.class, kClass, vClass));
        } catch (IOException e) {
            logger.error("json解析出错:" + json, e);
            return null;
        }
    }

    @Nullable
    public static <T> T nativeRead(String json, TypeReference<T> type) {
        try {
            return mapper.readValue(json, type);
        } catch (IOException e) {
            logger.error("json解析出错:" + json, e);
            return null;
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值