首页 > 解决方案 > 将子字符串应用于 axios 响应

问题描述

我需要在我的 axios 响应中获取一些字符串之间的文本,我有这种语法但不起作用,即使我尝试只将 response.data 值传递给 res 属性?并在控制台中打印结果,但我只收到一条未定义的消息。

提前谢谢你们。

<script>
    import Axios from 'axios';

    export default {

        data() {
            res: "",
            report: ""
        },

        methods: {
            sendTest() {
                Axios.post('http://server/',JSON.parse(Payload))
                    .then(response => {

                        this.res = response.data

                        this.report = this.substr(
                            this.res.indexOf('<TAG1>') + 1,
                            this.res.indexOf('</TAG1>')
                        )
                        console.log(this.report);
                    })
                    .catch(e => {
                        console.log(e.response)
                    });
            },
        }
    }
</script>

标签: javascript

解决方案


首先你应该检查是否response.data是一个字符串。如果是字符串,您必须解析您的 xml 数据。为此,您可以:

parser = new DOMParser();
xmlDoc = parser.parseFromString(response.data,"text/xml");
this.res = xmlDoc.getElementByTagName("tag")[0].textContent

但是你必须关心旧的 IE 版本。他们不支持 DOMParser。对于旧版浏览器,您必须添加:

if (window.DOMParser) {
  parser = new DOMParser();
  xmlDoc = parser.parseFromString(text,"text/xml");
} else {
  xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async = false;
  xmlDoc.loadXML(text);
} 
this.res = xmlDoc.getElementByTagName("tag")[0].textContent

如果您的 response.data 已经是已解析的 xml,您只需执行以下操作:

this.res = response.data.getElementByTag("tag")[0].textContent

推荐阅读