Laravel 4 ajax POST
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23252667/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel 4 ajax POST
提问by user3346696
I'm trying to make an ajax post in laravel 4, but I'm getting a 500 (Internal Server Error). I've looked over the internet and I can't see what I'm doing wrong.
我正在尝试在 laravel 4 中发布 ajax 帖子,但收到 500(内部服务器错误)。我查看了互联网,我看不出我做错了什么。
My ajax post (executed from 'http://flashwords.dev/app/public/words/level/1'):
我的 ajax 帖子(从“ http://flashwords.dev/app/public/words/level/1”执行):
$.ajax({
url: 'http://flashwords.dev/app/public/words/post_set',
type:'POST',
dataType:'JSON',
data:{
"words_correct": words_correct,
"words_false" : words_false
},
success:function(){
console.log("post success");
}
});
My route:
我的路线:
Route::post('words/post_set', array('as'=>'post_set', 'uses'=>'UserController@post_set'));
My function in the UserController:
我在 UserController 中的功能:
public function post_set(){
$correct = Input::get('words_correct');
$false = Input::get('words_false');
var_dump($correct);
}
Probably I'm looking over something dumb..
可能我在看一些愚蠢的东西..
Thanks in advance!
提前致谢!
回答by user3346696
So, I found out the problem.
所以,我发现了问题所在。
My code was fine, my url was fine, BUT because I'm trying to post data to my server laravel expect a csrf token sent with the post request.
我的代码很好,我的 url 很好,但是因为我试图将数据发布到我的服务器 laravel 期望随发布请求一起发送 csrf 令牌。
How? --> http://words.weareloring.com/development/laravel/laravel-4-csrf-tokens-when-using-jquerys-ajax/
如何?--> http://words.weareloring.com/development/laravel/laravel-4-csrf-tokens-when-using-jquerys-ajax/
It was a security issue.
这是一个安全问题。
回答by The Alpha
You should change your url
from:
你应该改变你url
的:
url: 'http://flashwords.dev/app/public/words/post_set',
To following:
以下:
url: 'words/post_set',
Hope your controllers are stored in the app/controllers
folder. You may also use this:
希望您的控制器存储在app/controllers
文件夹中。你也可以使用这个:
url: {{ route('post_set') }}
If this is in a .php
file and using blade, if not blade then remove the {{}}
and use echo
instead.
如果这是在.php
文件中并使用刀片,如果不是刀片,则删除{{}}
并使用刀片echo
。
回答by Sasanka Panguluri
Try using the Route's name to get it's full path and set it to the JSON request:
尝试使用 Route 的名称来获取它的完整路径并将其设置为 JSON 请求:
url:'<?=URL::route('post_set')?>',
type:'POST',
dataType:'JSON'
...stuff
I use such style in my own project, and it works just fine.
我在自己的项目中使用了这种风格,效果很好。