在Laravel中使用AJAX与数据库进行交互 [英] Using AJAX in Laravel to interact with database

查看:113
本文介绍了在Laravel中使用AJAX与数据库进行交互的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在基于模型,视图,控制器范例学习Laravel PHP框架.我一直试图将AJAX集成到我的简单启动器应用程序中……一个电话记录器.这是我通常放弃的地方.但是我拒绝了!

I'm learning the Laravel PHP framework, based on the Model, View, Controller paradigm. I'm stuck on trying to incorporate AJAX into my simple starter application...a phonecall logger. This is where I normally give up. But I refuse!

所以我有我的电话模型:

So I have my Phonecall Model:

class Phonecall extends Eloquent
{
// Creates an instance of the database object 
}

这是我的电话表格:

mysql> desc phonecalls;
+------------+------------------+------+-----+---------+----------------+
| Field      | Type             | Null | Key | Default | Extra          |
+------------+------------------+------+-----+---------+----------------+
| id         | int(10) unsigned | NO   | PRI | NULL    | auto_increment |
| who        | varchar(200)     | NO   |     | NULL    |                |
| what       | varchar(200)     | NO   |     | NULL    |                |
| created_at | datetime         | NO   |     | NULL    |                |
| updated_at | datetime         | NO   |     | NULL    |                |
| initiator  | varchar(200)     | NO   |     | NULL    |                |
| info       | text             | NO   |     | NULL    |                |
+------------+------------------+------+-----+---------+----------------+
7 rows in set (0.00 sec)

我的视图"列出了数据库中当前的所有呼叫(按谁和什么):

My View lists all calls (by who and what) currently in the database:

<!doctype html>
<html>
<head>
  <title>Title</title>
  <script type="text/javascript" 
           src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js">
</script>
</head>
<body>
<h1>Welcome</h1>
<p>Here's a list of recent phonecalls</p>
    <ul class="call-list">
    @foreach($phonecalls as $call)
        <li>{{ $call->who }} - {{ $call->what }} - 

        <a href="phonecalls/show/{{ $call->id }}">Show</a> | 

        {{ HTML::link('phonecalls/delete/'.$call->id, 'Delete') }} | 
        {{ HTML::link('phonecalls/update/'.$call->id, 'Update') }}
        </li>
    </ul>

    {{-- Placeholder for AJAX content --}}
    <div id="call-info">
    </div>
</body>
</html>

这是我简单的控制器:

 class Phonecalls_Controller extends Base_Controller {    

// Use $this within a method the same way you
// would use the object name outside of the class

public function get_index()
    {
            $phonecalls = Phonecall::all();
            return View::make('phonecalls.index')->with('phonecalls', $phonecalls);
    }    
// ************************************
// DISPLAY CALL INFO
public function get_show($call_id)
{
    $call = Phonecall::find($call_id);

            // WHAT GOES HERE?

}

我希望用户能够在视图中单击显示",然后 在...内显示通话信息...

I want the user to be able to click on "Show" in the view and have the call info display within the...

<div id="call-info">
</div>

视图中的

标记.

tags in the View.

这是干什么的...

我的get_show()方法

// ************************************
// SHOW CALL INFO
public function get_show($call_id)
{
$call = Phonecall::find($call_id);
return $call->info;
}

我的Javascript

//************************************
// Phonecall AJAX Example
//************************************
$(document).ready(function() {
  $('.call-list > li > a').click(function(e) {  // e=event
     e.preventDefault();
     var id = $(this).attr('id');
     $.get(BASE+'/phonecalls/show/'+id, function(data) {
     $("#call-info").html(data);
  })
});

推荐答案

这可以通过多种方式完成.

This can be done in many various ways.

首先,您可以这样做:

public function get_show($call_id)
{
    $call = Phonecall::find($call_id);

    return View::make('phonecalls.single')->with('phonecal', $call);

}

在这种情况下,您需要为单个电话创建一个模板并将其放在电话文件夹"中.

In which case you need to create a template for a single phonecall and put it in your phonecalls folder.

另一个选择是从Laravel应用返回JSON响应:

Another option is to return JSON response from the Laravel app :

public function get_show($call_id)
{
    $call = Phonecall::find($call_id)->first();

    return Response::eloquent($call);

}

另一种选择是使用javascript MVC框架使获取/更新AJAX数据等操作非常容易,例如Backbone JS或Angular JS可以做到这一点.

Another option is to use javascript MVC framework to make things like fetching/updating AJAX data very easy, for example Backbone JS or Angular JS can do that.

无论哪种方式,如果要处理AJAX数据,都需要构建一个API,以区分常规站点和AJAX数据后端.

Either way, if you want to do AJAX data you need to build an API to make a separation between regular site and AJAX data backend.

这是我的博客文章,其中包含有关如何完成此操作的许多详细信息: http://maxoffsky.com/code-blog/在laravel中开始构建REST API,在这里/

Here is my blog post with lots of details on how to accomplish this: http://maxoffsky.com/code-blog/building-restful-api-in-laravel-start-here/

此外,Dayle Rees的Code Happy撰写了Laravel中AJAX的精彩介绍,其中AJAX内容: codehappy.daylerees.com/ajax-content

Also, a great introduction for AJAX in Laravel is Code Happy by Dayle Rees, chapter AJAX content : codehappy.daylerees.com/ajax-content

如果您还有其他问题,请告诉我,如果您觉得我有所帮助,请批准此评论.谢谢!

Let me know if you have more questions, and approve this comment if you feel like I've helped. Thanks!

更新:

要从控制器(或Laravel路由)实际加载内容,您需要使用jQuery ajax,GET(加载数据)或POST(发布表单结果) 这是一个示例:

To actually load stuff in from the controller (or a Laravel route) you need to use jQuery ajax, GET(to load data) or POST(to post form results) Here's an example:

 $('#get-info').click(function(e) {  // e=event
        e.preventDefault();
        var BASE = "<?php echo URL::base(); ?>";
        // attempt to GET the new content
        $.get(BASE+'phonecalls/show/2', function(data) {
            $('#content').html(data);
        });

这篇关于在Laravel中使用AJAX与数据库进行交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆