试图用纯 js fetch 重写 jquery ajax获取获取正文

问题描述

在 Laravel 驱动的站点上,有一个 jquery 脚本控制购物车中商品的数量和总价。我正在尝试使用纯 js fetch 在购物车中重写 jquery ajax。但是,没有办法在get请求中通过body来获取!所需的参数(数量、产品类型)被传递到正文。如果你把身体,脚本发誓身体不应该。如果您将 body 更改为 data (或任何其他单词)。请求通过,但返回值中的认零,就像未传递此参数一样。如果将 get 方法更改为 post,则会出现 404 错误。请告诉我如何解决此问题?

旧脚本

$.ajax({
  type: "get",url: "{{ route('ajax.set.product.count') }}",data: {
    product_type: product_type,product_id: product_id,new_count: new_count,_token: "{{ csrf_token() }}"
  },dataType: "json",success: function(data) {
    console.log(data);
    if (data.error == 'no') {
      $('#productcount-1-' + index).val(data.new_count);
      $('#productprice-1-' + index).text(data.price_product);
      $('#productcount-2-' + index).val(data.new_count);
      $('#productprice-2-' + index).text(data.price_product);
      $('#price_all').text(data.price_all);
      if (data.poil_count > 0) $('.pcount').text(data.poil_count);
    }
  }
});

新脚本

fetch('{{ route('ajax.set.product.count') }}',{
    headers: {
      "Content-Type": "application/json","Accept": "application/json","X-Requested-With": "XMLHttpRequest"
    },method: 'get',credentials: "same-origin",body: JSON.stringify({
      product_type: product_type,_token: "{{ csrf_token() }}"
    }),}).then(function(response) {
  return response.json();
}).then(function(data) {
  console.log(data);
  if (data.error == 'no') {
    document.getElementById('productcount-1-' + index).value = data.new_count;
    document.getElementById('productprice-1-' + index).textContent = data.price_product;
    document.getElementById('productcount-2-' + index).value = data.new_count;
    document.getElementById('productprice-2-' + index).textContent = data.price_product;
    document.getElementById('price_all').textContent = data.price_all;
    if (data.poil_count > 0) document.querySelector('.pcount').textContent = data.poil_count;
  };
})

解决方法

GET 请求的参数放在 URL 的搜索字段中,因为没有正文。

const body = {
  product_type: product_type,product_id: product_id,new_count: new_count,_token: "{{ csrf_token() }}"
};
const params = Object.entries(body).map((k,v) => k + '=' + encodeURIComponent(v)).join('&');

fetch('{{ route('ajax.set.product.count') }}?' + params,{
    headers: {
      "Accept": "application/json","X-Requested-With": "XMLHttpRequest"
    },method: 'get',credentials: "same-origin"
  }).then(function(response) {
  return response.json();
}).then(function(data) {
  console.log(data);
  if (data.error == 'no') {
    document.getElementById('productcount-1-' + index).value = data.new_count;
    document.getElementById('productprice-1-' + index).textContent = data.price_product;
    document.getElementById('productcount-2-' + index).value = data.new_count;
    document.getElementById('productprice-2-' + index).textContent = data.price_product;
    document.getElementById('price_all').textContent = data.price_all;
    if (data.poil_count > 0) document.querySelector('.pcount').textContent = data.poil_count;
  };
})