我试图使用Laravel 5来获得Ajax响应,但它只是不会工作。这是错误我在Chrome调试器看到:在Laravel 5中没有Ajax响应
POST http://localhost:8000/getmsg 500 (Internal Server Error)send @ jquery.min.js:4ajax @ jquery.min.js:4getMessage @ ajax:10onclick @ ajax:25
这是message.php资源/浏览次数:
<html>
<head>
<title>Ajax Example</title>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script>
function getMessage(){
$.ajax({
type:'POST',
url:'/getmsg',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
$("#msg").html(data.msg);
}
});
}
</script>
</head>
<body>
<div id = 'msg'>This message will be replaced using Ajax.
Click the button to replace the message.</div>
<?php
echo Form::button('Replace Message',['onClick'=>'getMessage()']);
?>
</body>
</html>
这是我Ajaxcontroller.php:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class AjaxController extends Controller {
public function index(){
$msg = "This is a simple message.";
return response()->json(array('msg'=> $msg), 200);
}
}
然后我在路由中加入了web.php:
Route::get('ajax',function(){
return view('message');
});
Route::post('/getmsg','[email protected]');
尝试在JS添加此:$ .ajaxPrefilter(功能(选项,originalOptions,XHR){VAR 记号= $( '元[NAME = “csrf_token”]')ATTR( '内容'); 如果。 (令牌)返回xhr.setRequestHeader('X-XSRF-TOKEN',令牌); } });并尝试使用命名路线。编辑:这实际上不起作用,因为你没有在元中添加令牌。尝试使用主视图,在其中添加对所有页面都通用的所有内容,然后对其进行扩展。 Laracast有一些很棒的教程 – Indra