簡體   English   中英

如何在sweetalert2中訪問axios響應確認對話框

[英]How access axios response in sweetalert2 confirm dialog

即使在閱讀https://gist.github.com/domenic/3889970后 ,我可能還不完全理解承諾,我需要在sweetalert確認結果中訪問axios的響應。

這是我的代碼

axios
    .post("/posts", this.formData)
    .then(response => {
        if (typeof response.data.callback !== "undefined") {
            toastr.info("Created");
            swal.fire({
                title: "Success!",
                text: "you created new post",
                type: "success",
                showConfirmButton: true,
                confirmButtonText: "Close this",
                allowOutsideClick: false
            }).then(result => {
                if (result.value) {
                    window.location.replace(response.data.callback);
                }
            });;
        } else {
            toastr.error("Can't process this request");
        }
        this.formLoading = false;
    })

響應未定義,我想我不明白范圍如何在js中工作

這是一個你可以鏡像的例子。它需要一個從成功的API調用收到的URL(URL在API響應中),然后發送另一個請求......這應該向你證明你可以做任何事情你想要那里......開始一個不同的功能...字面上,*你想做的任何事情,你可以做* .then(...)塊...


CodeSandbox示例(使用鏈式警報和API調用進行更新)

編輯:更新我的答案,以顯示如何使用從API調用中檢索的數據....

正在使用的api數據的屏幕截圖


// Modal.vue component - holds the SweetAlert2

<template>
  <div>
    <button @click="swal();">CLICK ME TO LOAD API DATA USING SWEETALERT2</button>
    <div v-if="name != ''">
      <p>Name: {{ name }}</p>
    </div>
    <div v-if="homeworld != ''">
      <p>Homeworld: {{ homeworld }}</p>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      name: "",
      homeworld: ""
    };
  },
  methods: {
    swal() {
      let self = this;
      this.$swal
        .fire({
          title: "Click OK to load from: https://swapi.co/api/people/1/",
          showCancelButton: true,
          confirmButtonText: "OK",
          showLoaderOnConfirm: true,
          preConfirm: () => {
            return this.$axios
              .get("https://swapi.co/api/people/1/")
              .then(response => {
                if (response.status != 200) {
                  throw new Error("Something went wrong");
                }
                return response.data;
              })
              .catch(error => {
                this.$swal.showValidationMessage(`Request failed: ${error}`);
              });
          },
          allowOutsideClick: () => !this.$swal.isLoading()
        })
        .then(result => {
          if (result.value) {
            let v = result.value;
            self.name = v.name;
            this.$swal
              .fire({
                title: "Click Ok to redirect to another API call",
                text: `Going to (name:)"${v.name}"'s homeworld URL at: "${
                  v.homeworld
                }"`,
                showCancelButton: true,
                confirmButtonText: "OK",
                showLoaderOnConfirm: true,
                preConfirm: () => {
                  return this.$axios
                    .get(v.homeworld)
                    .then(response => {
                      if (response.status != 200) {
                        throw new Error("Something went wrong");
                      }
                      return response.data;
                    })
                    .catch(error => {
                      this.$swal.showValidationMessage(
                        `Request failed: ${error}`
                      );
                    });
                },
                allowOutsideClick: () => !this.$swal.isLoading()
              })
              .then(res => {
                if (res.value) {
                  self.homeworld = res.value.name;
                  this.$swal.fire({
                    title: "Homeworld",
                    text: JSON.stringify(res.value)
                  });
                }
              });
          }
        });
    }
  }
};
</script>

我讀了你的評論,你說回調是一個網址,我之前使用過axios和sweetalert,似乎你需要以json格式傳遞“回調”。 你做完了嗎? 如果沒有,這是使用Laravel的一個例子。 對不起我的英語不好。

Controller.php這樣

...
if(isAjax){
   return response()->json(['status'=>'info','messages'=>'Winter is coming!','rheader'=>'Warning!']);
}
...

查看(使用Sweetalert的Vue),一般的sweetalert也應該工作

...
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
axios.post("{{route('someroute')}}",{id:xid}) //you can ignore this, this is just passing id to the route
.then(response => {
  this.$swal(response.data.rheader, ""+response.data.messages+"", response.data.status);
  if(response.data.status=="success"){
    $("#something")).hide();
  }
})
.catch(e => {
  this.$swal("Warning", ""+e.response.data.messages+"", "warning");
});
...

希望它能幫到某人:)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM