jQuery通过ajax异步获取xml文件及xml转json字符串

jQuery通过ajax异步获取xml文件及xml转json字符串

1,ajax通过异步读取xml文件
在这里插入图片描述

<script>
    $(function () {
    
    
        //异步加载xml文件
        $.ajax({
    
    
            url:"vod/mp4/20180323173011-25701533_0_video.xml",
            type:"POST",
            async: true,  //异步请求
            cache: false,
            dataType: "text",  //返回值为文本(xml)
            success:function (result){
    
    
               var jsonvalue= xmlStr2XmlObj(result);  //将xml文件转换为json对象
               console.log(jsonvalue)
            },
            error:function (e) {
    
    
                console.log("异步失败:"+e);
            }
        });
    });
</script>

2,通过js将xml文件转换为json数据

<script>

	/**
     * xml字符串转换json数据
     * @param {
    
    Object} xml
     */
    function xmlObj2json(xml) {
    
    
        var xmlObj = xmlStr2XmlObj(xml);
        var jsonObj = {
    
    };
        if (xmlObj.childNodes.length > 0) {
    
    
            jsonObj = xml2json(xmlObj);
        }
        return jsonObj;
    }
	/**
	 * xml字符串转换xml对象数据
	 * @param {
    
    Object} xmlStr
	 */
	function xmlStr2XmlObj(xmlStr) {
    
    
	  var xmlObj = {
    
    };
	  if (document.all) {
    
    
	    var xmlDom = new ActiveXObject("Microsoft.XMLDOM");
	    xmlDom.loadXML(xmlStr);
	    xmlObj = xmlDom;
	  } else {
    
    
	    xmlObj = new DOMParser().parseFromString(xmlStr, "text/xml");
	  }
	  return xmlObj;
	}

    /**
     * xml转换json数据
     * @param {
    
    Object} xml
     */
    function xml2json(xml) {
    
    
        try {
    
    
            var obj = {
    
    };
            if (xml.children.length > 0) {
    
    
                for (var i = 0; i < xml.children.length; i++) {
    
    
                    var item = xml.children.item(i);
                    var nodeName = item.nodeName;
                    if (typeof(obj[nodeName]) == "undefined") {
    
    
                        obj[nodeName] = xml2json(item);
                    } else {
    
    
                        if (typeof(obj[nodeName].push) == "undefined") {
    
    
                            var old = obj[nodeName];
                            obj[nodeName] = [];
                            obj[nodeName].push(old);
                        }
                        obj[nodeName].push(xml2json(item));
                    }
                }
            } else {
    
    
                obj = xml.textContent;
            }
            return obj;
        } catch (e) {
    
    
            console.log(e.message);
        }
    }
</script>

Guess you like

Origin blog.csdn.net/weixin_44975322/article/details/121102790