Javascript 如何根据刀片模板中的数据库字段设置所选选项?

Javascript 如何根据刀片模板中的数据库字段设置所选选项?,javascript,php,html,laravel,laravel-blade,Javascript,Php,Html,Laravel,Laravel Blade,在我的laravel项目中,我有一个编辑表单,我想根据数据库字段设置所选选项。我该怎么做 我不能在视图中的php部分中使用$info变量。我想这是因为控制器部分 这是我的控制器: <?php public function Edit() { $idNew = $_GET['id']; $info = DB::table('test')->select('id','name','status')->where('id','=', $idNew)->get(

在我的laravel项目中,我有一个编辑表单,我想根据数据库字段设置所选选项。我该怎么做

我不能在视图中的php部分中使用$info变量。我想这是因为控制器部分

这是我的控制器:

<?php 
public function Edit()
{
    $idNew = $_GET['id'];
    $info = DB::table('test')->select('id','name','status')->where('id','=', $idNew)->get();
    $returnHTML = view('layouts.edit',['info'=> $info])->render();

    return response()->json([
    'html'=> $returnHTML
    ]);
}
?>

我的看法是:

<html>
<option value="enabled"  <?php if($info['status'] == 'enabled'){ echo ' selected="selected"'; } ?>>enabled</option>
</html>


使用数据数组并将其与视图一起传递

 public function Edit()
        {
        $data=array();
            $idNew = $_GET['id'];
            $data['info'] = DB::table('test')->select('id','name','status')->where('id','=', $idNew)->get();
             return view('layouts.edit')->with($data);
        }

你缺了一些零件

  • 在laravel控制器中,不要使用
    $\u GET
    数组。使用请求对象
  • 在blade文件中,不要使用php标记,请使用blade语法
  • 如果要从控制器显示刀片视图,请不要使用
    response()->json()
    函数,因为它用于ajax调用
  • 当您需要一条记录时,不要使用
    get()
    函数。使用
    first()
    函数
  • 您的控制器应为:

    use Illuminate\Http\Request;
    
    public function Edit(Request $request)
    {
        $idNew = $request->input('id', 'default_value');
        $info = DB::table('test')->select('id','name','status')->where('id','=', $idNew)->first();
    
        return view('layouts.edit', ['info'=> $info]);
    }
    
    <html>
        <option value="enabled" {!! $info['status'] == 'enabled' ? "selected='selected'" : "" !!}>enabled</option>
    </html>
    
    您的刀片文件应该是:

    use Illuminate\Http\Request;
    
    public function Edit(Request $request)
    {
        $idNew = $request->input('id', 'default_value');
        $info = DB::table('test')->select('id','name','status')->where('id','=', $idNew)->first();
    
        return view('layouts.edit', ['info'=> $info]);
    }
    
    <html>
        <option value="enabled" {!! $info['status'] == 'enabled' ? "selected='selected'" : "" !!}>enabled</option>
    </html>
    
    
    启用
    
    您是否打印了$data['info']任何数据?返回您的查看页面