php - Laravel:如何从下拉列表中选择更改后加载Ajax数据?

时间:2016-04-26 05:21:25

标签: php jquery ajax laravel laravel-5.2

我想在文本框中的下拉列表中选择一个值后加载一些ajax数据。

例如:从下拉列表中选择教师后,应加载教师剩余学分和credit_taken值。我如何用ajax做到这一点?

NB:此处教师值已从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>

这是我的控制器:

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);   
});

以下是查看页面

<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>

1 个答案:

答案 0 :(得分:8)

在route.php中设置:

public function show($id) { 
$post = Post::find($id);
return View::make('posts.show', compact('post')); 
}

));

你的控制器:TeachController.php

Route::get( '/ajaxteach', array(
'as' => 'ajaxteach',
'uses' => 'TeachController@get_teach'
在ajax脚本中你可以使用2种方式: 1)在javascript代码中使用绝对URL

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]);
}
}

2)使用路由

的url()
var base_url = 'http://localhost/laravel'
 $.ajax({
                type: "GET",
                url : base_url+"/ajaxteach",
                data : dataString,
                success : function(data){
                    console.log(data);
                }