从 AJAX 响应中获取 ID 并将该 ID 用于 Select2

Get Id From AJAX Response And Use The Id For Select2

我在控制器中编写HTML代码

public function edit($id)
{
    $user = User::find($id);
    $rolesForEdit = Role::pluck('name', 'name')->all();
    $userRole = $user->roles->pluck('name', 'name')->all();

    $html = '<div class="row">
     <div class="col-md-6">
        <label for="name">Name</label>
        <input value="' . $user->name . '" class="form-control"
            placeholder="Full Name" type="text" name="name" id="name" />
        <br>
        <label for="phone">Phone Number</label>
        <input value="' . $user->phone . '" class="form-control"
            placeholder="Phone Number" type="text" name="phone" id="phone" />
        <br>
    </div>
    <div class="col-md-6">
        <label for="roles">Role</label><br>
        <select style="width:220px;" name="rolesForEdit[]" multiple id="rolesForEdit"
            class="rolesForEdit form-control"></select>
        <br>
    </div> <!-- kanan -->
</div> <!-- row-->';

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

然后在视图中,我正在尝试获取 rolesForEdit id 并将其用于 select2。它不适用于这种方式。有什么解决办法吗?

$.ajax({
            url: "user/" + id + "/edit",
            method: 'GET',
            success: function(data) {
                //var roles = $($.parseHTML(data)).find("#rolesForEdit").html();
                //var roles = $(data).find('#rolesForEdit').text();
                //var roles = $(this).attr('rolesForEdit');
                //var roles = $($.parseHTML(data)).filter("#rolesForEdit");

                alert(roles);

                $(roles).select2({
                    ajax: {
                        url: '{{ url('searchrole') }}',
                        processResults: function(data) {
                            return {
                                results: data.map(function(item) {
                                    return {
                                        id: item.id,
                                        text: item.name
                                    }
                                })
                            }
                        }
                    }
                });
                $('#dataUserElement').html(data.html);
                $('#saveBtn').val("create-product");
                $('#user_id').val('');
                $('#productForm').trigger("reset");
                $('#modelHeading').html("Update User");
                $('#ajaxModel').modal('show');
            }
        });
    });

您的服务器 return json 作为响应,因此将 dataType: 'json' 添加到您的 ajax 呼叫。然后,将数据 return 附加到您的 dataUserElement 即:data.html 最后初始化您的 select2 .

演示代码 :

//suppose data is this :)
var data = {
  'html': '<div class="row"><div class="col-md-6"> <label for="name">Name</label><input value="abc" class="form-control" placeholder="Full Name" type="text" name="name" id="name" /><br><label for="phone">Phone Number</label><input value="12346" class="form-control" placeholder="Phone Number" type="text" name="phone" id="phone" /><br></div><div class="col-md-6"><label for="roles">Role</label><br><select style="width:220px;" name="rolesForEdit[]" multiple id="rolesForEdit" class="rolesForEdit form-control"></select><br></div></div>'
}

/*$.ajax({
url: "user/" + id + "/edit",
method: 'GET',
dataType:'json',//add this 
success: function(data) {*/
$('#dataUserElement').html(data.html); //then append this 
var roles = $('#dataUserElement').find(".rolesForEdit") //get select refernce
$(roles).select2({
  ajax: {
    url: "https://api.github.com/orgs/select2/repos", //this is for demo change it to your real url
    processResults: function(data) {
      return {
        results: data.map(function(item) {
          return {
            id: item.id,
            text: item.name
          }
        })
      }
    }
  }
});
//all other codes modal ..etc etc
/*}
});*/
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" />
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.full.min.js"></script>

<div id="dataUserElement">
</div>