[英](Laravel + Ajax) The url is wrong and AJAX is not working
Here is my code in blade i wanna trying to click button, then send the id to the controller with AJAX. 这是我想尝试单击按钮的刀片中的代码,然后使用AJAX将ID发送给控制器。
<input type="button" onclick="javascript:del_click({{$leftnew->id}});" style="background-image:url(img/delete.jpg);background-size:cover;width:5px;height:12px; border:none; line-height:0;text-indent:-9999px; ">
AJAX part AJAX部分
function del_click(data){
//alert(data);
var request = new XMLHttpRequest();
$.ajax({
type :"POST",
url :"{{url('/deleteNews')}}}",
dataType:"json",
data :{ data:data },
success :function(response) {
alert("thank u");
},
error: function(e) {
console.log(e.responseText);
}
});
Route.php Route.php
Route::post('deleteNews','NewsController@deleteNews');
Controller 调节器
public function deleteNews(Request $request){
$news_id = $request->news_id;
$news= NewstbEloquent::find($news_id);
if($news->delete()){
return redirect('/')->with('msg','success');
}
else{
return redirect('/')->with('msg','error');
}
}
when i clicked the button, it will get the response with.... 当我单击按钮时,它将得到响应。
http://localhost/YangMing567/public/deleteNews%7D
i have no idea. 我不知道。 what happened?
发生了什么? why there get the "%7D"?
为什么会有“%7D”? i didnt set that in the url, and it got the response with the %7D back.
我没有在URL中设置它,它得到了带有%7D的响应。
it look like not pass the route page, then get the error because of the URL wrong. 看起来好像没有通过路线页面,则由于网址错误而导致错误。 Have anyone know the reason?
有人知道原因吗?
You have extra }
in url. 网址中有额外的
}
。 Remove it. 去掉它。
{{url('/deleteNews')}}
Also you need to add CSRF too. 另外,您还需要添加CSRF。 Otherwise you will get HttpException.
否则,您将获得HttpException。
Add this meta to head
tag: 将此meta添加到
head
标签:
<meta name="csrf-token" content="{{ csrf_token() }}">
And before ajax request add this: 在ajax请求之前添加以下内容:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
So your script must be: 因此,您的脚本必须是:
<script>
function del_click(data){
//alert(data);
var request = new XMLHttpRequest();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type :"POST",
url :"{{url('/deleteNews')}}",
dataType:"json",
data :{ data:data },
success :function(response) {
alert("thank u");
},
error: function(e) {
console.log(e.responseText);
}
});
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.