我尝试将axios从数组发布到api php文件并逐个获取响应而不仅仅是一个请求。我读了一些关于axios.all()的内容,但无法弄清楚我是javascript的新手。
<div id="app">
<center>
<div id="area">
<textarea v-model="sent" name="sent" id="sent" cols="30" rows="10" class="form-control">
</textarea>
<br>
<button v-on:click="insert" class="btn btn-default">Send</button>
</div>
<div id="good" v-for="message of messages">
<span><h2>Good</h2></span>
{{ message }}
</div>
</center>
</div>
这是vuejs代码。
<script>
new Vue({
el:'#app',
data:{
sent:[],
messages:[]
},
methods:{
insert:function (){
const vm = this;
splitz.forEach(function(entry){
axios.post('/one.php', {
sent: vm.entry
}).then(response => {
vm.messages.push(response.data.onefinal) ;
console.log(response.data);
}
).catch(function(error){ console.log(error); });
}
}
},
computed:{
splitz: function () {
return this.sent.split('\n')
}
}
});
</script>
答案 0 :(得分:0)
你可以这样做:
// Create an array of post requests from splitz array
var requests = splitz.map(entry => axios.post('/one.php', { sent: this.entry }))
// Send all requests using axios.all
axios.all(requests)
.then(results => results.map(response => response.data.onefinal))
.then(newMessages => {
console.log('New Messages:', newMessages)
this.messages.push.apply(this.messages, newMessages)
})
修改:逐个发送请求:
insert: function() {
var vm = this;
function sendRequest(arr, i) {
var entry = arr[i];
axios.post('/one.php', { sent: entry }).then(function (response) {
vm.messages.push(response.data.onefinal);
if (i < arr.length - 1) {
sendRequest(arr, ++i);
}
})
.catch(function (error) {
console.log(error);
});
}
sendRequest(this.splitz, 0);
}