[英]Passing data from view to controller using Ajax in Laravel
I am trying to pass two variables to my controller using ajax.我正在尝试使用 ajax 将两个变量传递给我的 controller。 There are no errors but the data is null when I get it in the controller.
没有错误,但是当我在 controller 中获取数据时,数据为 null。
Web.php Web.php
Route::get('/donate/select-card', 'CardController@chooseCard')->name('select-card');
CardController.php CardController.php
public function chooseCard()
{
$from = Input::get("fromAmount");
// $to = $request->input('toAmount');
dd($from);
}
'null' is the output here
'null' 是 output 这里
Script.js脚本.js
fromAmount = $(this).find('p span:nth-child(1)').text().split("₹ ")[1];
toAmount = $(this).find('p span:nth-child(2)').text().split("₹ ")[1];
$.ajax({
type:'GET',
url: '/donate/select-card',
data: { fromAmount : fromAmount, toAmount : toAmount }
});
What I want is to have the fromAmount & toAmount in my controller.我想要的是在我的 controller 中有 fromAmount 和 toAmount。
Thanks in advance.提前致谢。
This is the ajax data from network:这是来自网络的 ajax 数据:
public function chooseCard(Request $request)
{
return $request->all();
}
** Inject the Request class ** 注入请求 class
** See the response from dev tool. ** 查看开发工具的响应。
That one was tricky:)那个很棘手:)
In your HTML you have a link that is wrapping this call to the ajax.在您的 HTML 中,您有一个链接将这个调用包装到 ajax。 This is messing with
这是在搞砸
<a href="/donate/select-card">
<button type="button" onclick="test123()">click here for ajax Call</button>
</a>
So clicking on this will send you to "/donate/select-card" but won't be trough the ajax.因此,单击此按钮会将您发送到“/donate/select-card”,但不会通过 ajax。 For the same reason, once you try to use POST, you get:
出于同样的原因,一旦你尝试使用 POST,你会得到:
The GET method is not supported for this route.
此路由不支持 GET 方法。 Supported methods: POST
支持的方法:POST
The href is with priority and it is GET while the route is expecting a POST. href 具有优先级,它是 GET,而路由需要 POST。
Make sure you remove all links and default behaviours around the html you use to call the ajax call then use GET or POST as you wish.确保删除用于调用 ajax 调用的 html 周围的所有链接和默认行为,然后根据需要使用 GET 或 POST。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.