ajax请求json和xml数据及对json和xml格式数据的解析


最近写插件的时候,遇到xml格式的数据,以前用xml比较少,一直都是json格式。这里对json和xml做个总结。

一、ajax请求json数据并解析

ajax的写法:

$.ajax({
      url: 'url',//接口的url
      type: 'POST',
      dataType: 'json',//返回数据的类型是json
      success : (data) => {
        console.log(data);//data是返回的数据,是String格式
        let result=JSON.stringify(data); //将data转换成json格式 
      },
      error : () => {
        alert('请求失败');
      }
    });

json数据解析:

例如上面代码,success回调函数中取得了json格式的数据result。假设数据为:

{
	id : 'mike',
	name : 'laowang',
	datas : 
	[
		[age : 1, passw : 'hhh'],
		[age : 2, passw : 'gghh']
	]
}

解析数据只要用点(.)就行了。

result.id; //mike
result.datas[1]; // [age : 2, passw : 'gghh']

请求json经常出现的跨域报错:

Access to XMLHttpRequest at ‘http://xxxx.com/xxx’ from origin ‘null’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
有时候一些接口经常会出现这个错误。解决方案是把dataType的值json改为jsonp。

二、ajax请求xml数据并解析

ajax的写法:

这个和json差不多,就是把数据格式改成xml。

$.ajax({
      url: 'url',//接口的url
      type: 'POST',
      dataType: 'xml',//返回数据的类型是json
      success : (data) => {
        console.log(data);//data是返回的数据,类似于一个xml文件
      },
      error : () => {
        alert('请求失败');
      }
    });

xml数据解析:

xml数据的解析,推荐使用jQuery里面的方法。
如上代码,在success的回调函数拿到数据data之后。假设格式如下:

<?xml version="1.0" encoding="UTF-8"?>
<resp>
<city>北京</city>
<updatetime>16:27</updatetime>
<shidu>23%</shidu>

<yesterday>
    <date_1>18日星期六</date_1>
    <high_1>高温 3</high_1>
    <low_1>低温 -4</low_1>
    <day_1>
        <type_1>多云</type_1>
    </day_1>
    <night_1>
        <type_1></type_1>
    </night_1>
</yesterday>

<forecast>
<weather>
    <date>19日星期天</date>
    <high>高温 6</high>
    <low>低温 -4</low>
    <day>
        <type></type>
    </day>
    <night>
        <type></type>
    </night>
</weather>

<weather>
    <date>20日星期一</date>
    <high>高温 5</high>
    <low>低温 -6</low>
    <day>
        <type></type>
    </day>
    <night>
        <type>多云</type>
    </night>
</weather>
</forecast>
</resp>

解析xml的写法一般为:主要是$().find().each()方法,注意这是一个循环方法

	$(data).find("resp").each(function(){//在data里面找resp标签
          let updateTime=$(this).find("updatetime").text();//把updatetime标签里面的值取出来
        });
发布了57 篇原创文章 · 获赞 43 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_43592352/article/details/104055331
今日推荐