我正在尝试将一个变量连接到我在 ajax 中的 url 链接。变量 $news
是处理通知 ID 的变量。
$(document).on("click", "#viewList", function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var $news = $(this).prop("value");
$.ajax({
type: "get",
url : '{{url("admin/recipients/", $news)}}', //returning an error undefined variable news
data: {newsID : $news},
success: function(store) {
console.log(store);
$('#rec').text(store);
},
error: function() {
$('.alert').html('Error occured. Please try again.');
}
});
});
在我的 web.php 中,它的路由在路由组内。
Route::group(['middleware' => 'auth:admin'], function () {
Route::prefix('admin')->group(function() {
Route::get('/recipients/{news}', 'Admin\NewsController@recipients');
});
});
那么我怎样才能让它工作呢?顺便说一下,我的 ajax 在 blade.php
文件中。
最佳答案
Blade 服务器不存在$news,因为它在服务器呈现页面时执行。所以你的javascript还没有被执行。要使这项工作正常,请将您的 js 代码更改为:
$(document).on("click", "#viewList", function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var news = $(this).prop("value");
$.ajax({
type: "get",
url : '{{url("admin/recipients")}}' + '/' + news,
data: {newsID : news},
success: function(store) {
console.log(store);
$('#rec').text(store);
},
error: function() {
$('.alert').html('Error occured. Please try again.');
}
});
});
关于php - 如何在ajax URL路由中添加变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54994496/