Laravel中使用GET方法通过Ajax传递参数失败求助
问题原因分析
你的Ajax请求问题出在URL路径参数的处理和响应数据的解析两个核心点:
- URL错误:Ajax配置里的
url: "{{ url('helpers/get-item-details/{code}') }}"会把{code}当作静态字符串,实际请求的URL会变成helpers/get-item-details/{code}?code=100390。此时路由会把路径参数{id}解析为字符串{code},所以控制器返回的就是{code}。 - 响应解析错误:控制器直接返回字符串
$itemId,但你在success回调里尝试访问response.hs_code——由于响应不是JSON对象,这会导致取不到值。
解决方案
步骤1:修正Ajax请求的URL
你的路由使用的是路径参数({id}),需要把参数值直接拼到URL路径中,而非放在data里:
// 假设code是动态获取的,比如从输入框或变量中 const code = 100390; $.ajax({ type: "GET", // 直接拼接路径参数 url: `/helpers/get-item-details/${code}`, success:function(response) { console.log(response); // 控制器返回纯字符串,直接赋值即可 $('input[name="hs_code"]').val(response); }, error: function(jqXHR, textStatus, errorThrown) { console.log("Invalid response"); console.log(jqXHR.responseText); alert(jqXHR.responseText); } });
如果想更规范地使用Laravel路由生成,可以先给路由命名:
// 路由配置添加名称 Route::get('/helpers/get-item-details/{id}', 'App\Helpers\Helper@getItemDetails')->name('helper.item.details');
再在Blade模板中生成基础URL并动态替换参数:
// 获取带占位符的基础路由,替换为实际code值 const baseUrl = "{{ route('helper.item.details', ['id' => '__CODE__']) }}"; const code = 100390; const url = baseUrl.replace('__CODE__', code); $.ajax({ type: "GET", url: url, success:function(response) { console.log(response); $('input[name="hs_code"]').val(response); }, error: function(jqXHR, textStatus, errorThrown) { console.log("Invalid response"); console.log(jqXHR.responseText); alert(jqXHR.responseText); } });
步骤2:修正控制器响应(可选,更规范)
如果希望返回JSON格式响应(方便后续扩展字段),修改控制器方法:
class Helper { public static function getItemDetails($itemId){ return response()->json([ 'hs_code' => $itemId ]); } }
此时success回调里的response.hs_code就能正常取值。
验证
修改后,Ajax请求的URL会和你直接在浏览器访问的helpers/get-item-details/100390完全一致,即可正常返回参数值。
内容的提问来源于stack exchange,提问作者Aditya Amit
相关产品推荐
相关产品推荐

