【发布时间】:2018-08-06 12:57:38
【问题描述】:
基本上我正在尝试确定服务器返回的是 json 还是字符串
然后转换该 json 并在循环中显示它的每个元素,或者只显示那个字符串。
我想要达到这样的目标:
发送带有一些数据的发布请求
如果 post bodyText 包含 { 和 } 则将其解析为 json 并在 html 中绘制
<li>
其他
- 只需打印 bodyText。
new Vue({
el: '#app',
data: {
user: {
UserLogin: 'test',
UserEmail: 'test',
UserPassword: 'test'
},
responseArr: []
},
methods: {
submit() {
this.$http.post('http://api.com/validate', this.user)
.then(response => {
return "OK";
},
error => {
return error.bodyText;
})
.then(data => {
console.log(data);
if (data.includes("{")) {
console.log("if");
data = JSON.parse(data);
const arr = [];
for (let key in data) {
arr.push(data[key]);
}
this.responseArr = arr;
}
else
{
console.log("else");
const arr = [];
arr.push(data);
this.responseArr = arr;
}
}
);
},
}
});
<div id="errorList">
<li v-for="element in responseArr">
<div v-if="responseArr.includes('{')">
<ul class="errorScope">
<li v-for="nested_element in element">{{nested_element}}</li>
</ul>
</div>
<div v-else>
<li>{{element}}</li>
</div>
<button v-on:click="submit">Submit</button>
【问题讨论】:
-
你可以调用
JSON.parse()并在抛出异常时捕获异常。 -
@Pointy 我在“以前的版本”中尝试过,但最后由于某种原因我仍然无法正确地将数据注入到 html 中。例如 vue 不会刷新它。
-
你可以用
if (typeof data === "string")代替data.includes("{"),这意味着你有字符串并在if块中做JSON.parse(data) -
在
- {{元素}}
标签: javascript vue.js frontend