在Laravel中,与blade.php文件中与ajax的关系如下:
{{ foreach($schhols as $school) }}
<td>{{ $school->user->name }}</td>
<td>{{ $school->user->address}}</td>
<td>{{ $school->user->country}}</td>
{{ endforeach }}
但是在带有laravel的ajax中怎么做?
function load() {
$.get('/read', function (data){
$('#data').html("");
$.each(data, function (key, val) {
$('#data').append("<tr>"+
"<td>"+val.id+"</td>"+
"<td id='ename'>"+val.name+"</td>"+
"<td id='eaddress'>"+val.address+"</td>"+
"<td id='ecountry'>"+val.country+"</td>"+
"<td>"+
"<button class='btn btn-warning' id='edit' data-id="+val.id+">Edit</button>"+
"<button class='btn btn-danger' id='delete' data-id="+val.id+">Delete</button>"
+"</td>"+
+"</tr>")
});
});
}
这会发生吗?
"<td id='ename'>"+val.user.name+"</td>"+
"<td id='eaddress'>"+val.user.address+"</td>"+
"<td id='ecountry'>"+val.user.country+"</td>"+
答案 0 :(得分:1)
在您的控制器中
public function read(Request $request){
$schhols = Schhol::get();
// if ajax request return response in json
if($request->ajax()){
return response()->json($schhols);
}else{
// else return data to view
return view('schhol_view',compact('schhols'))
}
}
如果您是从前端发送的ajax请求:
<script>
function load() {
$.ajax({
url: '/read',
type:'GET',
dataType:'json',
contentType:'application/json',
success:function (data){
$('#data').html("");
$.each(data, function (key, val) {
$('#data').append("<tr>"+
"<td>"+val.user.id+"</td>"+
"<td id='ename'>"+val.user.name+"</td>"+
"<td id='eaddress'>"+val.user.address+"</td>"+
"<td id='ecountry'>"+val.user.country+"</td>"+
"<td>"+
"<button class='btn btn-warning' id='edit' data-id="+val.user.id+">Edit</button>"+
"<button class='btn btn-danger' id='delete' data-id="+val.user.id+">Delete</button>"
+"</td>"+
+"</tr>")
},error:function(err){
console.log('Error loading data');
}
});
}
</script>