I don't know how to get the response of a successful Axios call and display the success message.
There is a button named "Change Workflow Order", which has an onClick function.
<div style="display: flex"> <button class="btn btn-info change-workflow" onclick="changeWorkflowOrder()"> Change Workflow Order </button> <span style="color: green; margin-left: 5px;" id="alert_msg"> </span> </div>
This is the onClick function. The changeWorkflowOrder function runs an Axios call.
function changeWorkflowOrder() { const response = axios.post(js_site_url + '/sort-detail', $('#sortable').sortable("toArray"), { headers: { 'Content-Type': 'multipart/form-data' } }) }
I want to capture the successful response of the Axios call and if the response of the Axios call is successful, display the success message in the HTML span tag. The message must only be displayed for 4 seconds. After 4 seconds, the success message must be hidden.
I try to create this. This is the changeWorkflowOrder function I tried.
function changeWorkflowOrder() { const response = axios.post(js_site_url + '/sort-detail', $('#sortable').sortable("toArray"), { headers: { 'Content-Type': 'multipart/form-data' } }); response.then((result) => { $("#alert_msg").html(result.data.success ? "Success" : "Order change successfully"); clearTimeout(timeoutId); timeoutId = setTimeout(function() { $("#alert_msg").hide(); }, 4000); }); }
This code displays the error message correctly. But after 4 seconds the error message is shown, the "Order change successfully" message is not hidden, I think the Axios call response capture part is incorrect.
How can I capture the response of an Axios call and display a success message for 4 seconds in an HTML span tag.
P粉8846670222023-09-14 00:16:16
I recommend first creating an axios client for your api/webservice:
import axios from 'axios'; export const myApiClient = axios.create({ baseURL: '...' /* 在你的情况下,这将是js_site_url */, headers: { 'Content-Type': 'multipart/form-data' /* 这当然可以在任何特定实例调用此客户端时被覆盖 */ } });
Then rewrite your onclick function and implement delay, refer to this Stack Overflow answer :
import {myApiClient} from '...'; /* 如果你决定将其存储在单独的文件中,请导入你的客户端 */ const delay = ms => new Promise(res => setTimeout(res, ms)); async function changeWorkflowOrder() { const myPostData = $('#sortable').sortable("toArray"); return await myApiClient.post('/sort-workflow-detail-manage', myPostData) .then(await res => { const alertMsg = res.data?.success ? '成功' : '成功更改顺序'; $("#alert_msg").html(alertMsg); await delay(4000).then(_ => $("#alert_msg").hide()); }) .catch(err => /* 在这里处理失败的api请求 */); }