【问题标题】:Pull data from database using Eloquent and Laravel使用 Eloquent 和 Laravel 从数据库中提取数据
【发布时间】:2014-03-06 20:46:54
【问题描述】:

这里是 Ajax 新手问题:

我想使用 Ajax 从数据库中获取结果,并根据用户在表中输入的内容显示该行。

我想知道如何做到这一点:

这是我的控制器:

     public function pricing()
  {
    $q = Input::get('term');
    if($q && $q != ''){
        $searchTerms = explode(' ', $q);
        $query = DB::table('pricing');

        if(!empty($searchTerms)){

            foreach($searchTerms as $term) {
                $query->where('unit', 'LIKE', '%'. $term .'%');
            }
        }

        $results = $query->paginate(5);
        $results->appends(array('term' => Input::get('q')));

        dd($results);


        return View::make('layouts.buyresults', compact('results'));
    }
}

我的表单只是一个输入字段,名称为“term”和一个引导类。

雄辩的模型

  <?php

     class Pricing extends Eloquent {

      protected $table = 'pricing';

     }

因此基于此如何设置路线,我目前有:

    Route::get('site/where-to-buy', 'HomeController@pricing');

我在表单中的操作是相同的,那么如何在不离开页面且不刷新的情况下实现这一点?所以用户输入一个数字,比如说 10,它们在数据库中匹配,然后 ajax 请求拉出该行并显示在一个表中。

提前致谢:)

【问题讨论】:

  • 你有没有尝试过?您的问题在 StackOverflow 上被认为过于宽泛
  • 仅 dd($results);并试图传递给一个视图,我知道这是一个广泛的问题,但只是试图根据我的代码获取一些示例以供学习。

标签: php jquery ajax laravel-4


【解决方案1】:

如果你想要一个动态表,你可以考虑使用像datatables 这样的插件。该插件还提供搜索、排序和过滤选项。如果不能使用插件,您可以监听 input 相关事件并使用 jQuery 实用函数向服务器发送 Ajax 请求(datatables 在后台也使用 jQuery 的 ajax 方法):

$('#theInput').on('keyup', function() {
   $.get('url', { term: $.trim(this.value) }, function(data) {
      if (data.count > 0) {
          // appending the rows, `html` overwrites the tbody's existing rows
          $('#theTable tbody').html(data.view); 
      } else {
        // Nothing found, notify the user
      }
   }, 'json');
}); 

这个请求期望得到一个 JSON 字符串,其中包含 viewcountcount 应该是查询结果的数量,view 是匹配行的 HTML,现在在你的控制器中您可以调用生成 HTML 的视图并检查请求的类型:

if ( Request::ajax() )
{
   $response = array();
   $response['count'] = $query->count(); 
   $response['rows'] = $query->get(); 
   $response['view'] = View::make('row_generator')
                           ->with('rows', $response['rows'])
                           ->render();
   return Response::json($response); 
}
else 
{ 
  // handle the non-ajax requests
}

当然还有很多其他方法可以检索/操作数据,您也可以在客户端生成表格行。

【讨论】:

  • 好的,这让我能更好地理解,非常感谢。
猜你喜欢
  • 1970-01-01
  • 2016-08-13
  • 2019-07-18
  • 2014-08-08
  • 1970-01-01
  • 1970-01-01
  • 2015-01-28
  • 2016-12-06
  • 1970-01-01
相关资源
最近更新 更多