php - Laravel:如何在从下拉列表中选择更改后加载 Ajax 数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36855854/
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
php - Laravel : how to Load Ajax data after selected changes from dropdown?
提问by User57
I want to load some ajax data after selected a value from dropdown in textbox.
我想在从文本框中的下拉列表中选择一个值后加载一些 ajax 数据。
Eg:After selecting a teacher from dropdown, teachers remaining credit and credit_taken value should be load. How do I do it with ajax?
例如:从下拉列表中选择一名教师后,应加载教师剩余学分和 credit_taken 值。我如何用ajax做到这一点?
NB:Here teacher value has selected from another dropdown selecting in 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>
Here is my controller:
这是我的控制器:
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);
});
Here is the view Page:
这是视图页面:
<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>
回答by Ehsan
in route.php set :
在 route.php 设置:
Route::get( '/ajaxteach', array(
'as' => 'ajaxteach',
'uses' => 'TeachController@get_teach'
) );
) );
your controller : TeachController.php
你的控制器: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]);
}
}
in ajax script you can use 2 way : 1) use absolute url in javascript code
在 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);
}
2) use url() with route
2) 将 url() 与路由一起使用
$.ajax({
type: "POST",
url : "{{url('ajaxteach')}}",
data : dataString,
success : function(data){
console.log(data);
}