window.location.href不是刷新/重新加载页面

时间:2019-09-16 12:45:41

标签: javascript jquery ajax

在函数window中创建refreshcart()函数。location.href分配给currentUrl。但是当在else块窗口中进行ajax调用时.location.href = currentUrl,true;它不会刷新页面。

$(document).ready(function() {
  var productForm = $(".form-product-ajax")

  productForm.submit(function(event) {
    event.preventDefault();
    //console.log("Form is not sending!")
    var thisForm = $(this)
    //var actionEndpoint = thisForm.attr("action");
    var actionEndpoint = thisForm.attr("data-endpoint");
    var httpMethod = thisForm.attr("method");
    var formData = thisForm.serialize();

    $.ajax({
      url: actionEndpoint,
      method: httpMethod,
      data: formData,
      success: function(data) {
        console.log("success: ", data)
        //currentPath = window.location.href --if cart is in current path--
        if (window.location.href.indexOf("cart") != -1) {
          refreshCart()
        }
      },
      error: function(errorData) {
        console.log("error: ", errorData)
      }
    })
  })

  function refreshCart() {
    console.log("In current cart")

    var currentUrl = window.location.href


    var refreshCartUrl = '/api/cart/'
    var refreshCartmethod = "GET";
    var data = {};

    $.ajax({
      url: refreshCartUrl,
      method: refreshCartmethod,
      data: data,
      success: function(data) {
        console.log("success: ", data)
        console.log("If block starts")
        if ([data.products].length > 0) {
          console.log("Condition checked")
        } else {
          console.log("It came here")
          window.location.href = currentUrl, true;
        }
      },
      error: function(errorData) {
        console.log("Oh no! error: ", errorData)
      }
    })
  }
})

1 个答案:

答案 0 :(得分:0)

只需重新使用页面即可

window.location.reload()