【问题标题】:Laravel 5.5 jQuery ajax methodLaravel 5.5 jQuery ajax 方法
【发布时间】:2018-08-15 12:02:18
【问题描述】:

大家好

我遇到了一个特殊的问题。以下代码是我的控制器功能

public function populateIndustry(Request $request) {

    if($request->isMethod('post')) {
        $var = "Post Method";
    } else {
        $in_id = $request->industry_id;
        //$var = $request->industry_id;
        $var = IndustryAction::where('industry_id',$request->industry_id)->toSql();
    }   
    return response()->json($var);
}

这是我的 jQuery 代码:

$(".edit_industry").click(function(e){
  $.ajax({
    url: "populateIndustry",
    type: "get",
    data: { 
      '_token':$('input[name=_token]').val(),
      'industry_id':$(this).data('id'),
    },
    success: function(data) {
      console.log(data);
    },
    error: function(data) {
      console.log(data);
    }
  });    
});

如您所见,我正在尝试检查查询,发现此查询中未填充 industry_id 字段:

select * from `industries` where `industry_id` = ?

而这行代码我发现返回了正确的 id

//$var = $request->industry_id;

谁能指出我的错误?

【问题讨论】:

  • 你错过了理解应该返回的内容。 select * from industries where industry_id = ? 是正确的。 ? 是预期的,因为它被理解为 id 是一个变量。
  • 这种情况下应该怎么办呢?请指导。因为我期待像 { select * from industries where industry_id = 1} 这样的查询
  • 等一下,我会把它放在答案中
  • 当然。非常感谢

标签: jquery laravel laravel-5.5


【解决方案1】:

你试过了吗?

 $var = IndustryAction::where('industry_id',$request->industry_id)->get();

你有什么错误吗?你检查错别字了吗?

【讨论】:

  • 请参阅我已编辑问题并向您展示了控制台中显示的查询
  • tosql() 非常适合快速查看 SQL。但它不包括查询绑定,只有一个 ?用于插入它们的位置。
  • 好的。非常感谢您消除了我的疑问。明白了
【解决方案2】:

如果你知道查询格式,也许你可以这样做:

$query = IndustryAction::where('industry_id',$request->industry_id);
$stub_sql = $query->toSql();
$values = $query->getBindings();

$var = str_replace( '?', $values[0], $stub_sql );

【讨论】:

  • 非常感谢。急需帮助
【解决方案3】:

你可以这样做。

启用查询日志,然后

//enable the log first
\Illuminate\Support\Facades\DB::enableQueryLog();

 $var = IndustryAction::where('industry_id',$request->industry_id)->get();

 return \Illuminate\Support\Facades\DB::getQueryLog();

你会得到带有类似绑定的json

query:  "select * from `industry_action` where `id` = ?"
bindings: 
    0:  12
time:   0.62

“12”是你的身份证

【讨论】:

  • 非常感谢。卡了一整天
猜你喜欢
  • 2018-04-03
  • 1970-01-01
  • 2018-08-12
  • 2020-04-30
  • 1970-01-01
  • 2018-04-05
  • 2018-07-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多