我试图在laravel中使用ajax发布数据,但似乎无法正常工作。我跟着以下是我的代码
login.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="csrf_token" content="{{ csrf_token() }}" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<style type="text/css">
</style>
<script type="text/javascript">
$(document).ready(function(){
$('.send-btn').click(function(){
console.log($('input[name=email]').val());
$.ajax({
url: 'login',
type: "post",
data: {'email':$('input[name=email]').val(), '_token': $('input[name=_token]').val()},
success: function(data){
console.log($('input[name=email]').val());
alert(data);
}
});
});
});
</script>
</head>
<body>
<div class="secure">Secure Login form</div>
{!! Form::open(array('url'=>'account/login','method'=>'POST', 'id'=>'myform')) !!}
<div class="control-group">
<div class="controls">
{!! Form::text('email','',array('id'=>'','class'=>'form-control span6','placeholder' => 'Email')) !!}
</div>
</div>
<div class="control-group">
<div class="controls">
</div>
</div>
{!! Form::button('Login', array('class'=>'send-btn')) !!}
{!! Form::close() !!}
</body>
</html>
和route.php
Route::get('account/login', function() {
return View::make('login');
});
Route::post('account/login', 'AccountController@login');
并在控制器中
public function login() {
// Getting all post data
if(!Request::ajax()) {
$data = Input::all();
print_r($data);
}
}
每当我尝试提交表单不起作用时。我尝试在onclick jquery中使用alert,但它显示了警告消息。有谁能说出它为什么不起作用?
注意:这个问题已经提出但没有找到任何对我有用的答案
更新
<script type="text/javascript">
$(document).ready(function(){
$('.send-btn').click(function(){
console.log($('input[name=email]').val());
$.ajax({
url: 'login',
type: "post",
data: {'email':$('input[name=email]').val(), '_token': $('input[name=_token]').val(),'_method': 'POST'},
success: function(data){
console.log($('input[name=email]').val());
alert(data);
}
});
});
});
</script>
在控制台安全性中,我收到以下错误
[HTTP/1.0 500 Internal Server Error 115ms]
Update 2
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="csrf_token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<style type="text/css">
</style>
<script>
$(document).ready(function() {
$('#frm').on('submit', function (e) {
alert();
e.preventDefault();
var title = $('#title').val();
var body = $('#body').val();
var published_at = $('#published_at').val();
$.ajax({
type: "POST",
url: 'http://localhost/demo/public/articles/articles',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
dataType: 'JSON',
data: {title: title, body: body, published_at: published_at},
success: function( data ) {
$("#ajaxResponse").append(data.msg);
alert(data);
}
});
});
});
</script>
</head>
<body>
{!! Form::open(['url' => 'articles', 'id' => 'frm']) !!}
<p>
{!! Form::label('title', 'Title:') !!}
{!! Form::text('title') !!}
</p>
<p>
{!! Form::label('body', 'Body:') !!}
{!! Form::textarea('body') !!}
</p>
<p>
{!! Form::label('published_at', 'Date:') !!}
{!! Form::input('date', 'published_at', date('Y-m-d'), ['class' => 'form-control']) !!}
</p>
<p>
{!! Form::submit('Submit Article', ['id' => 'submit']) !!}
</p>
{!! Form::close() !!}
</body>
</html>
route.php
Route::resource('articles', 'ArticlesController');
文章控制器
public function store()
{
print_r(Request::all());
}
更新2
[2015-08-28 06:23:03]
local.ERROR: exception 'Illuminate\Session\TokenMismatchException' in D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\VerifyCsrfToken.php:53
Stack trace:
#0 [internal function]: Illuminate\Foundation\Http\Middleware\VerifyCsrfToken->handle(Object(Illuminate\Http\Request), Object(Closure))
#1 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(124): call_user_func_array(Array, Array)
#2 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\View\Middleware\ShareErrorsFromSession.php(54): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#3 [internal function]: Illuminate\View\Middleware\ShareErrorsFromSession->handle(Object(Illuminate\Http\Request), Object(Closure))
#4 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(124): call_user_func_array(Array, Array)
#5 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Session\Middleware\StartSession.php(62): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#6 [internal function]: Illuminate\Session\Middleware\StartSession->handle(Object(Illuminate\Http\Request), Object(Closure))
#7 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(124): call_user_func_array(Array, Array)
#8 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse.php(37): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#9 [internal function]: Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse->handle(Object(Illuminate\Http\Request), Object(Closure))
#10 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(124): call_user_func_array(Array, Array)
#11 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Cookie\Middleware\EncryptCookies.php(59): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#12 [internal function]: Illuminate\Cookie\Middleware\EncryptCookies->handle(Object(Illuminate\Http\Request), Object(Closure))
#13 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(124): call_user_func_array(Array, Array)
#14 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode.php(42): Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#15 [internal function]: Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode->handle(Object(Illuminate\Http\Request), Object(Closure))
#16 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(124): call_user_func_array(Array, Array)
#17 [internal function]: Illuminate\Pipeline\Pipeline->Illuminate\Pipeline\{closure}(Object(Illuminate\Http\Request))
#18 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php(103): call_user_func(Object(Closure), Object(Illuminate\Http\Request))
#19 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(122): Illuminate\Pipeline\Pipeline->then(Object(Closure))
#20 D:\xampp\htdocs\demo\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php(87): Illuminate\Foundation\Http\Kernel->sendRequestThroughRouter(Object(Illuminate\Http\Request))
#21 D:\xampp\htdocs\demo\public\index.php(54): Illuminate\Foundation\Http\Kernel->handle(Object(Illuminate\Http\Request))
#22 {main}
答案 0 :(得分:3)
您正在犯多个错误:
1-您的csrf令牌位于meta标记中(不在输入字段中):
2-meta标签名称为csrf_token(但是您使用错误的名称,即_token来调用它)
3- csrf令牌不在值属性中,但在内容属性中
所以您必须这样称呼
_token': $('meta[name=csrf_token]').attr('content')
无论如何,有如下所示的更简单方法:
_token:"{{csrf_token()}}"
不需要它
_token: $('meta[name=csrf_token]').attr('content')
改为使用以下语句:
_token:"{{csrf_token()}}" will do the same.
完整示例:
$.ajax
({
type: "POST",
dataType : 'json',
url: "{{route('routeName')}}",
data: {_token:"{{csrf_token()}}", data: data}
}).done( function(data){
console.log('Ajax was Successful!')
console.log(data)
}).fail(function(){
console.log('Ajax Failed')
});
答案 1 :(得分:2)
表格完美无缺。
您忘记在您的ajax表单数据中发送"_method": "post"
。
Laravel正在使用Symfony路由,它使用一个名为 _ method 的特殊参数来路由到您的路由定义。
答案 2 :(得分:2)
我看到的是一个在ajax定义中调用的错误网址,应该是:
url: 'http://localhost/demo/public/articles',
上面的网址应该存储一篇文章。对于帖子登录,您应该使用:
url: 'http://localhost/demo/public/login',
请注意,如果您的网站会更改域名网址,您可以通过标题中的javascript初始化网址:
<script>
var login_url = '{{ url("login") }}';
</script>
然后你可以把它称为:
$.ajax({
type: "POST",
url: login_url,
答案 3 :(得分:1)
我立即注意到了一些事情。首先,您已将POST路由(在routes.php中)设置为&#39; account / login&#39;,但您要将$ .ajax网址设置为“登录”。您需要将其设置为&#39; / account / login&#39;,就像您在表单网址和(最重要的)路由文件中一样。
另外,因为你正在使用Laravel {!! Form :: xxx()!!}结构,您不需要包含&#39; =&gt;&#39; POST&#39;。这将自动添加,CSRF令牌也将自动添加。 http://laravelcollective.com/docs/5.0/html#opening-a-form
另外,登录&#39;只有当请求不是 AJAX时,您的Controller中的功能才会运行,但您尝试通过AJAX请求发送,是否正确?只需要深入研究几件事。希望它有所帮助。
答案 4 :(得分:1)
从异常中可以看出,您遇到了CSRF令牌的问题。因此,某种程度上你无法发送令牌,这是你必须追踪的内容。
在更新前的原始问题中,您需要从隐藏的表单元素发送令牌,例如:'_token': $('input[name=_token]').val()
Form::open
应该在表单中添加字段,但可能存在问题,因此我建议您查看页面的来源以确保存在隐藏的表单元素<input type="hidden" name="_token" value="asdfasfd">
。
和/或您只需在浏览器的控制台中输入$('input[name=_token]').val()
即可确保达到该值。
更新2&#39;您决定将CSRF令牌移至元标记并使用标题发送,但元的名称为csrf_token
,但您在$ .ajax选项中将其引用为csrf-token
(短划线)而不是使用下划线。)
对于这两种情况,追踪问题的最佳方法是有效地使用浏览器控制台:
_token
字段 - 或 - X-CSRF-TOKEN
标题以及它们是否为空。答案 5 :(得分:0)
我认为问题出在App/Http/Middleware/Authenticate.php
尝试更改此
public function handle($request, Closure $next)
{
if ($this->auth->guest())
{
if ($request->ajax())
{
return response('Unauthorized.', 401);
}
else
{
return redirect()->guest('auth/login');
}
}
return $next($request);
}
对此:
public function handle($request, Closure $next)
{
return $next($request);
}
答案 6 :(得分:0)
问题是您使用的是URL而不是直接路径。 Laravel几乎会覆盖并重定向任何http发布或获取的内容。打开浏览器开发人员工具并查看请求,实际请求的URL与ajax调用中的URL不同。
请参见下面的示例,完整的URL不起作用。绝对路径。
$.ajax
({
type: "POST",
dataType : 'text',
url: "../../public/head-editor-api/index.php",
data: {
website_hosting_server: website_hosting_server,
website_hosting_username: website_hosting_username,
website_hosting_password: website_hosting_password
}
}).done( function(data){
alert(data);
}).fail(function(){
alert("error");
});