[英]How to POST array of objects of multiple form radio inputs to PHP using axios and vue?
我的 web 應用程序中有一個多申請人表格,其中有一個單選按鈕選擇器部分。 我設法在每個新的申請表中修復了單選按鈕,但現在將數據發布到 PHP 和 MySQL 數據庫時遇到問題。 My question is how do I go about posting an array of object to PHP and save it to MySQL database using axios?
我試圖找到有關該主題的教程,甚至找到其他問題,但我沒有找到答案。
let app = new Vue({ el: "#app", data: { buttons: [{ val: null }] }, methods: { addNewRadios(evt) { evt.preventDefault(); this.buttons.push({ val: null }); //console.debug(this.buttons); }, onSubmit(evt) { evt.preventDefault(); const formData = app.toFormData(app.buttons); console.log(formData); //What to do here??? }, toFormData(obj) { let formData = new FormData(); for (var key in obj) { formData.append(key, obj[key]); } return formData; } } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <h1>Multiple radio buttons VueJS</h1> <div id="app"> <div class="radio"> <form @submit='onSubmit' method="post"> <div v-for="(button, index) in buttons"> <b>Index {{ index }}:</b> <label:for="'rButton-' + index">option 1</label> <input type="radio":name="'rButton-' + index" value="value-1" v-model="button.val"> <label:for="'rButton-' + index">option 2</label> <input type="radio":name="'rButton-' + index" value="value-2" v-model="button.val"> </div> <br> <button @click="addNewRadios">Add radios</button> <button type="submit">Submit</button> </form> </div> <div> </div> </div>
在這里,我對您的代碼進行了一些修改。 使用按鈕值構建表單數據,然后使用 axios 發布數據,
let app = new Vue({
el: "#app",
data: {
buttons: [{
val: null
}]
},
methods: {
addNewRadios(evt) {
evt.preventDefault();
this.buttons.push({
val: null
});
//console.debug(this.buttons);
},
onSubmit(evt) {
evt.preventDefault();
const formData = app.toFormData(app.buttons);
// What to do here???
// post data to your backend server.
axios({
method: 'post',
url: 'http://example.com/my-url',
data: formData,
}).then(response => {
console.log('Response:', response);
// upon successful post request, you will see the response from the backend server here.
}).catch(err => {
console.log('Error:', err);
// and in case of any error at the backend server.
});
},
toFormData(obj) {
let formData = new FormData();
for (let key in obj) {
formData.append(key, obj[key].val); // appending the button `val` property here, instead of the entire object.
}
return formData;
}
}
});
然后在后端服務器中,處理發布數據。 您應該在那里收到您發送的按鈕值數組。
我希望這有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.