Use*_*r57 6 php ajax jquery laravel laravel-5.2
我想在文本框中的下拉列表中选择一个值后加载一些ajax数据.
例如:从下拉列表中选择教师后,应加载教师剩余学分和credit_taken值.我如何用ajax做到这一点?
注意:此处教师值已从Ajax中的另一个下拉列表中选择
<script>
$('#teacher').on('change',function(e){
var teach_id = $('#teacher option:selected').attr('value');
var info=$.get("{{url('ajax-teach')}}",{teach_id:teach_id});
info.done(function(data){
$.each(data,function(index,subcatObj){
/// Here will be the loaded code ///
});
});
info.fail(function(){
alert('ok');
});
});
</script>
Run Code Online (Sandbox Code Playgroud)
这是我的控制器:
Route::get('ajax-teach',function(Request $request){
$teach_id = $request::input(['teach_id']);
$teachers=\App\Teacher::where('teacher_id','=',$teach_id)->get();
return Response::json($teachers);
});
Run Code Online (Sandbox Code Playgroud)
这是视图页面:
<div class="form-group">
<label for="">Teacher</label>
<select class="form-control input-sm" required name="teacher_id" id="teacher" >
<option value=""></option>
</select>
</div>
<div class="form-group">
<label>Credit to be Taken</label>
<input type="text" name="credit_taken" id="credit_taken" class="form-control" required placeholder="Credit to be Taken">
</div>
<div class="form-group">
<label>Remaining Credit</label>
<input type="text" name="remaining_credit" class="form-control" required placeholder="Remaining Credit">
</div>
Run Code Online (Sandbox Code Playgroud)
在route.php中设置:
Route::get( '/ajaxteach', array(
'as' => 'ajaxteach',
'uses' => 'TeachController@get_teach'
Run Code Online (Sandbox Code Playgroud)
));
你的控制器:TeachController.php
class TeachController extends Controller
{
public function get_teach(Illuminate\Http\Request $request)
{
$teach_id = $request->get('teach_id');
$teachers=\App\Teacher::where('teacher_id','=',$dept_id)->get();
return response()->json(['response' => $teachers]);
}
}
Run Code Online (Sandbox Code Playgroud)
在ajax脚本中你可以使用2种方式:1)在javascript代码中使用绝对URL
var base_url = 'http://localhost/laravel'
$.ajax({
type: "GET",
url : base_url+"/ajaxteach",
data : dataString,
success : function(data){
console.log(data);
}
Run Code Online (Sandbox Code Playgroud)
2)使用url()和路由
$.ajax({
type: "POST",
url : "{{url('ajaxteach')}}",
data : dataString,
success : function(data){
console.log(data);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10189 次 |
| 最近记录: |