问题描述
想通过AJAX访问Show函数数据,但是当我在路由中传递id变量时返回错误
Contoller
public function show($id)
{
$features['UnitFeatures'] = UnitFeatures::find($id);
return $features;
}
查看刀片文件
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var feature_id = $('#unitFeatures').val();
$.ajax({
url: '{{ route('unitfeatures.show',feature_id) }}',// error in this line when i pass feature_id value to route
type: 'GET',dataType: 'json',success: function(response){
console.log(response);
}
});
});
请给我一个解决方法
解决方法
问题是您无法在{{}}
PHP代码中访问JS变量。
您将必须获取路线uri,并在JS代码中手动替换占位符。
您可以通过以下代码获取Route的URI:
\Route::getRoutes()->getByName('unitfeatures.show ')->uri
这将uri作为一个字符串返回,如下所示:/sometext/{id}
现在,您可以使用str.replace()
或您喜欢的任何功能,只需将 {id} 替换为 feature_id 。
var feature_id = $('#unitFeatures').val();
var origUrl = '{{ \Route::getRoutes()->getByName('unitfeatures.show ')->uri}}';
$.ajax({
url: origUrl.replace('{id}',feature_id),type: 'GET',dataType: 'json',success: function(response){
console.log(response);
}
});
});
,
您在PHP代码中使用Javascript变量时遇到的问题您可以在将PHP代码执行为字符串后使用Javascript变量。
$.ajax({
url: "{{ route('unitfeatures.show') }}"+'/'+feature_id,success: function(response){
console.log(response);
}
});
});