从数据库获取数据并将其显示在警报中

时间:2019-02-12 06:47:38

标签: ajax laravel

我是laravel的新手,我想从数据库中获取数据并使用ajax在Alert上显示

我的路线:

Route::get('getforajax/{id}','Home@getforajax');

我的控制器:

    public function getforajax ($id)
{
    $result=DB::select('select * from employees where empid =?',[$id]);
    return $result;
}

我的观点:

            $('#empid1').keyup(function() {
            $.ajax({
                url: 'getforajax/3',
                type: 'GET',
                data: data,
                dataType: 'json',
                success: function (data) {
                    alert(data.empid);
                }
            });
        });

2 个答案:

答案 0 :(得分:1)

您可以从控制器返回json。

@RunWith(SpringRunner.class)
@SpringBootTest
public class LegacyBeansAutoConfigurationTest {
  @Autowired
  ApplicationContext context;

@Test
public void contextLoads() {
    Assertions.assertThat(context.getBeanNamesForType(LegacyBeansAutoConfiguration.Legacy1.class)).isNotNull();
    Assertions.assertThat(context.getBeanNamesForType(LegacyBeansAutoConfiguration.Legacy2.class)).isNotNull();
    Assertions.assertThat(context.getBeanNamesForType(LegacyBeansAutoConfiguration.Legacy3.class)).isNotNull();
}
}

但是,结果将是所有查询结果行的数组。因此,即使您期望查询得到一个结果,它仍然会为您提供单个条目的数组。

return response()->json($result, 200);

此外,您可以对其进行如下改进:

在Javacript中,您需要执行以下操作:

[
  [
    id => something,
    name => something
  ]
]

但是,您需要确保数据在那里。使用雄辩的模型从Id加载条目:

data[0].empId

然后您直接做:

$result = Employee::findOrFail($employeeid);

答案 1 :(得分:1)

您应该尝试以下操作:

use App\Employee; //employee table's model

public function getforajax ($id)
{
    $result=Employee::find($id);
    return $result;
}
相关问题