我尝试使用ajax获取对象的值。我将该对象的所有属性存储在数组中。现在,我需要在ajax成功函数上访问该数组。 这是我的控制器。
public function sub(Request $request)
{
if($request->ajax())
{
$id = $request->get('selected');
if($id != null) {
$sub = DB::table('companies')->where('id', $id)->first();
if ($sub)
{
$subComp = [
'name' => $sub->name,
'address' => $sub->address,
'contact' => $sub->contact_num
];
}
}
}
echo json_encode($subComp);
}
这是我的html。
<div id="subCompany">
<input type="text" name="subname">
<input type="text" name="subaddress">
<input type="text" name="subcontact">
</div>
我的脚本:
$.ajax({
type: 'GET',
url: "{{ route('leader') }}",
dataType:'json',
data: {'selected': selected},
success: function (subComp) {
alert('success');
$('#subCompany[name="subname"]').val(subComp.name);
$('#subCompany[name="subaddress"]').val(subComp.address);
$('#subCompany[name="subcontact"]').val(subComp.contact);
}
});
答案 0 :(得分:1)
我认为问题是您的选择器
更改此:
$('#subCompany[name="subname"]').val(subComp.name);
$('#subCompany[name="subaddress"]').val(subComp.address);
$('#subCompany[name="subcontact"]').val(subComp.contact);
对此:
var subCompanyEl = $('#subCompany'); // its just for caching
subCompanyEl.find('input[name=subname]').val(subComp.name);
subCompanyEl.find('input[name=subaddress]').val(subComp.address);
subCompanyEl.find('input[name=subcontact]').val(subComp.contact);