【问题标题】:How to pass multiple data to controller?如何将多个数据传递给控制器​​?
【发布时间】:2020-12-25 00:29:47
【问题描述】:

这是两个选择框。当我同时选择产品和保修值时,它应该传递给控制器​​。那么我应该如何传递?

<select id="products">
    <option value="1">Mobile</option>
     <option value="2">Laptop</option>
</select>

<select id="warrant">
    <option value="1">1 Years</option>
     <option value="2">2 years</option>
     <option value="3">3 years</option>
</select>

这是我的脚本文件

$('#products').change(function () {
     var product_id=$(this).val();
})
$('#warrant').change(function () {
     var warrant_id=$(this).val();
})

我想在下面的代码中传递 Controller 中的那些warrant_id 和 product_id 那么我该如何传递呢?

<script>
fetch('http://127.0.0.1:8000/api/productChart'+{
  warrant_id,product_id
})
    .then(response => response.json())
    .then(data => {
            this.sales = data.sales;
            this.start = data.start;
            this.to = data.end;
        });
 </script>

这是我的路线

Route::get('/productChart','Controller@productChart');

【问题讨论】:

  • 目前两者都没有通过?
  • @AlwaysHelping nope 我只是在尝试。但是我怎么能呢?

标签: javascript jquery laravel api


【解决方案1】:

您可以使用formData 使用fetch API 在发布请求中将您的variable 数据发送/传递到您的后端。

将variable (product_id /warrant_id) 定义为可访问的全局变量,并将它们的值分配回变量,然后使用formData.append 方法将data 添加到您的formData 以便能够发送它你的 laravel backend.

此外,如果您要发送更多 data,您可以简单地将 append 更多值发送到您的 formData。

var product_id
var warrant_id

$('#products').change(function() {
  product_id = $(this).val();
})
$('#warrant').change(function() {
  warrant_id = $(this).val();
})

function callFetch() {
  var formData = new FormData(); //initialize form Data
  formData.append('product_id', product_id); //append product_id
  formData.append('warrant_id', warrant_id);//append warrant_id

  //Post Request
  fetch('http://127.0.0.1:8000/api/productChart', {
      body: formData,
      method: "post"
    })
    .then(response => response.json())
    .then(data => {
      //do something with data
    });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="products">
  <option value="1">Mobile</option>
  <option value="2">Laptop</option>
</select>

<select id="warrant">
  <option value="1">1 Years</option>
  <option value="2">2 years</option>
  <option value="3">3 years</option>
</select>

<button onclick="callFetch()">
 Post Data
</button>

【讨论】:

  • 那么我可以用get方法代替post吗?
  • @SauravShrestha 不! Post 方法是用来发布数据没有得到的。
  • @SauravShrestha 真的。您需要确保您复制的是我上面提供的确切内容。这是工作小提琴:jsfiddle.net/jrgae527/1 - 检查它正在发送数据的网络控制台。
  • @SauravShrestha 这是一个工作截图 - 正在发送数据:ibb.co/87Rr8cG
  • 好的..兄弟..我需要问你但是
猜你喜欢
  • 2010-11-10
  • 1970-01-01
  • 2016-09-10
  • 2020-06-22
  • 2020-11-30
  • 2016-01-05
  • 1970-01-01
  • 1970-01-01
  • 2021-04-27
相关资源
最近更新 更多