我试图从 sweetalert 输入中获取列表的名称,并使用 axios 将其传递到 CategoryController,以便使用 add_list() 函数将其添加到数据库
SideVav.vue:
const { add_list } = useList()
const listName=ref()
function addList() {
const inputValue = ''
Swal.fire({
title: 'Add List',
input: 'text',
inputLabel: 'Enter the list name',
inputValue: inputValue,
showCancelButton: true,
background: '#fefbe9',
confirmButtonColor: '#007E33',
allowOutsideClick: false,
inputValidator: (value) => {
if (!value) {
return 'You need to write something!'
}
}
}).then((result) => {
if (result.isConfirmed) {
listName.value = result.value
add_list(listName.value)
}
})
}
lists.js :
const add_list = async (data) => {
let formData = new FormData();
formData.append('name', data);
axios.post('/api/dashboard/addlist', formData).then(response => {
console.log(response)
if (response.data.success) {
Swal.fire({
title: 'Success!',
text: response.data.success,
icon: 'success',
confirmButtonText: 'Ok',
confirmButtonColor: '#007E33',
background: '#fef6dd',
allowOutsideClick: false,
})
}else{
alert('err')
}
}).catch(function (error) {
console.log(error);
})
}
这里axios并没有在CategoryController中发送formData。
CategoryController.php:
public function add_list(Request $request)
{
$request->validate([
'name' => 'required'
]);
$category = $request->all();
Category::create($category);
return response()->json(['success' => "The list '" . $request->name . "' successfully created"]);
}
最后,类别表中没有添加任何列表。
请帮助我!
我相信,既然您要发布 formData,并且 axios 假定为 json,您可能必须传递一个标头,告诉服务器您要发布的是 formdata。
const headers = {
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
axios.post('/api/dashboard/addlist', formData, headers).then(response => {})
这可能会有所帮助。
有人对此有答案吗!!!