Laravel中json_decode解析Ajax内容返回null的解决求助
解决Laravel控制器无法获取Ajax传递的HTML内容问题
我来帮你排查下问题,你遇到json_decode返回null的情况主要有两个原因,咱们一步步解决:
问题1:Ajax参数名存在多余空格
你在Ajax的data里写的是'query ' : query(注意query后面多了个空格),而控制器里用$request->Input(['query'])去获取,参数名不匹配,导致拿到的是null,自然json_decode(null)会返回null。
问题2:无需对HTML内容使用json_decode
你的query是从富文本编辑器拿到的HTML字符串,并不是JSON格式的字符串,所以完全不需要用json_decode解析,直接获取即可。
修改后的代码
控制器代码
// 直接获取query参数,不需要json_decode $query = $request->input('query'); $product = Product::where('name','=',$request->input('name'))->first(); $user= User::where('id','=',$product->auth_id)->first(); Mail::to($user->email)->queue(new Email($query)); return response()->json($query);
Ajax调用代码
$('#SupportForm button').on('click', function(e) { const query = tinyMCE.activeEditor.getContent() console.log(query ) e.preventDefault(); $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ type: "POST", url: '{{url("/supportEmail")}}', // 去掉query后面的空格,参数名和控制器保持一致 data: {'query' : query ,'name':$("#support_product").val()}, success: function(data) {console.log(data);}, error:function(data) { } }); });
额外提示
如果之后你确实需要传递JSON格式的数据,记得在Ajax里用JSON.stringify()把数据转成JSON字符串,然后控制器再用json_decode解析,但这次你的场景完全不需要这么做。
内容的提问来源于stack exchange,提问作者Hola
相关产品推荐
相关产品推荐

