2014-04-21 54 views
0

我的窗體上有兩個選擇框。我的第二個選擇框的值取決於第一個選擇框。我想從我的第二個盒子上的數據庫檢索值。如何解決它? 這裏是我的視圖代碼從Laravel中的選擇框中檢索數據庫中的值

First: {{ Form::select('first', 1, 10) }}  

Second: {{ Form::select('second', $value) }}   

我希望當我選擇第一個選擇框的值來調用這個函數。 這裏是我的控制器代碼

public function getValue() 
{  
    $keyword = Input::get('first');  
    $value = [];      

    $tables= DB::table('table') 
       ->where('first', '=', $keyword)              
       ->get(); 

    foreach ($tablesas $tables) { 
     $value[] = $table->value;   
    }   

    return View::make('view.index') 
      ->with('value', $value);     
} 

我應該使用AJAX或JavaScript。如何解決它。請幫助

回答

0

如果您想在第一個值發生變化時獲得第二個值,則需要使用第一個值執行ajax請求。在服務器端,當你獲得第一個值時,找到與db中的第一個值匹配的第二個值。然後只是返回值(laravel自動轉換爲json)。

看來,

First: {{ Form::select('first', $first, 10, array('id' => 'first')) }}  

Second: {{ Form::select('second', array(), null, array('id' => 'second')) }} 

在JS,

$(document).on('change', '#first', function() { 

    var first = $(this).find(':selected').val(); 

    $.post('ajax/get_second', {first: first}, function (data) {   
     if (data) { 
      var html = ''; 
      $.each(data, function (key, val) { 
       html += '<option value="'+key+'">' + val + '</option>'; 
      } 
      $('#second').html(html); 
     } 
    }, 'JSON'); 
}); 

在控制器,

public function getSecond() 
{ 
    $first = Input::get('first'); 

    $tables= DB::table('table') 
      ->where('first', $first) 
      ->get(array('key', 'value')); 

    foreach ($tables as $tables) { 
     $result[$table->key] = $table->value ;   
    } 

    return $result; 
} 
+0

但如何調用** ** getSecond功能? – satjan

+0

當您更改#first選擇框時,將通過ajax調用'ajax/get_second'。所以,你需要做的是指向具有路由的controller @ method。在route.php中, 'Route :: post('ajax/getSecond',array('uses'=>'ControllerName @ getSecond'));' –

相關問題