【问题标题】:How to get data using ajax passing parameter (laravel)如何使用ajax传递参数(laravel)获取数据
【发布时间】:2017-09-03 04:53:29
【问题描述】:

我想通过执行具有 id = $id 的 SQL 查询来填充表。

代码 ajax:

$('#ingredientTable').DataTable({
    "ajax": {
        "url": "api/ingredients",
        "type": "post",
         "data" : {
             '_token': token,
              "id" :  '1' ,
          }
    },
    "columns":[
      {data:'name', name: 'ingredients.name'},
    ],
});

在路线中:

route::post('api/ingredients', function() {
    return Datatables::of(
        DB::select('SELECT * FROM ingredients 
              INNER JOIN ingredient_product ON ingredient_product.ingredient_id = ingredients.id 
              WHERE ingredients.id=' . $id . ' ;'))
        ->make(TRUE);
});

我收到此错误:

POST http://localhost:8080/pizzeria/public/api/ingredients 500(内部服务器错误)和 DataTables 警告:表 id=ingredientTable - Ajax 错误。有关此错误的更多信息,请参阅http://datatables.net/tn/7

【问题讨论】:

  • 你永远不会从帖子中获得 id。此外,您应该使用参数而不是尝试引用您自己的变量,这会让您为 SQL 注入打开大门。
  • @aynber select() 是参数化的,只有 DB::raw() 暴露你。
  • @Ohgodwhy 以该格式发送 $id 未参数化。
  • @aynber 你是对的,它应该是DB::raw() 无论如何,这很可能是 500 ISE 的原因。 select() 使用不正确。我会更新我的答案来解决这个问题。
  • 您实际上可以像这样使用 DB::select。其他东西会引发错误。

标签: php jquery mysql ajax laravel


【解决方案1】:

Route 中的r 应大写

Route::post

您的select() 语句不正确,因为您需要使用DB::raw() 来允许自己编写原始SQL。但是,正如@aynber 所指出的,您也会将自己暴露在 SQL 注入中。相反,应该这样做:

DB::table('ingredients')
    ->join('ingredient_product', 'ingredients.id', 'ingredient_product.ingredients_id')
    ->where('ingredients.id', request()->has('id') ? request()->get('id' : null)
    ->select('*') 
    ->get();

这将保护您免受 SQL 注入并正确利用 Laravel 的 Query Builder

【讨论】:

    猜你喜欢
    • 2014-08-04
    • 2018-02-26
    • 2015-10-10
    • 2018-06-08
    • 1970-01-01
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    相关资源
    最近更新 更多