我试图将ajax
成功回调输出到视图中:
控制器:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class AjaxTestController extends Controller
{
public function ajax()
{
$nomi = array();
$nomi[0]['name'] = "alex";
$nomi[0]['surname'] = "zambonin";
$nomi[1]['name'] = "ciccio";
$nomi[1]['surname'] = "pasticcio";
return view('testAjax')->with('nomi',$nomi);
}
}
查看:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<title>Laravel</title>
<link rel="stylesheet" href="{{ URL::asset('assets/stylesheets/frontend.css') }}">
</head>
<body>
@foreach ($nomi as $nome)
{{ $nome['name'] }}<br/>
@endforeach
</body>
<script src="{{ URL::asset('assets/javascript/frontend.js') }}"></script>
<script>
$.ajax({
url: 'testajax',
dataType: 'json',
type: 'GET',
success: function(data) {
alert(data);
}
})
</script>
</html>
我可以在html页面中正确显示json数据,但我不能在javascript警报中得到它。
另外,我在firefox控制台上有404错误;请参阅此UInt64
如何让它发挥作用? 谢谢 亚历
答案 0 :(得分:3)
您获得的是404,因为URL / testajax不存在。您需要先为此创建路线。然后来自控制器的响应需要是JSON响应,如下所示:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
class AjaxTestController extends Controller
{
public function myFancyWebsite()
{
return view('testAjax');
}
public function ajaxResponse()
{
$nomi = array();
$nomi[0]['name'] = "alex";
$nomi[0]['surname'] = "zambonin";
$nomi[1]['name'] = "ciccio";
$nomi[1]['surname'] = "pasticcio";
return response()->json($nomi);
}
}
现在你的ajax请求应该指向那个只返回JSON响应的方法。但是你需要先在routes.php中创建一个路由:
Route::get('somepage', 'AjaxTestController@myFancyWebsite');
Route::get('testajax', 'AjaxTestController@ajaxResponse');