Is it possible to identify whether the server has returned JSON data or just a string?
If so, how can I parse the JSON and display each element in a loop, or simply display the string.
I envision achieving something like this:
Send a POST request with some data
If the post bodyText contains curly braces ( { and } ), treat it as JSON and create
<li>
elements in HTML
Otherwise,
- just print the bodyText as is.
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>