在 Laravel 中使用 AJAX 与数据库交互

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15624075/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 07:38:43  来源:igfitidea点击:

Using AJAX in Laravel to interact with database

jquerylaravel

提问by Jaystew

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!

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

So I have my Phonecall Model:

所以我有我的电话模型:

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

Here's my phonecalls table:

这是我的电话表:

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>

Here's my simple Controller:

这是我的简单控制器:

 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.

视图中的标签。



UPDATE:

更新:

Here's what did it...

这是它做了什么......

My get_show() method

我的 get_show() 方法

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

My Javascript

我的 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);
  })
});

采纳答案by msurguy

This can be done in many various ways.

这可以通过多种方式来完成。

First, you can do this :

首先,你可以这样做:

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.

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

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

另一种选择是从 Laravel 应用程序返回 JSON 响应:

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

    return Response::eloquent($call);

}

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.

另一种选择是使用 javascript MVC 框架使获取/更新 AJAX 数据之类的事情变得非常容易,例如 Backbone JS 或 Angular JS 可以做到这一点。

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.

无论哪种方式,如果你想要做 AJAX 数据,你需要构建一个 API 来区分常规站点和 AJAX 数据后端。

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/

这是我的博客文章,其中详细介绍了如何完成此操作:http: //maxoffsky.com/code-blog/building-restful-api-in-laravel-start-here/

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

此外,Laravel 中 AJAX 的一个很好的介绍是 Dayle Rees 的 Code Happy,AJAX 内容章节: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!

如果您有更多问题,请告诉我,如果您觉得我有所帮助,请批准此评论。谢谢!

UPDATE:

更新:

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:

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

 $('#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);
        });

回答by edunuke

it took me a while to figure out as the examples in the webz are kind of confusing making reference to changing headersto account for csrftoken and so on. Here is an example and I hope it helps someone else.

我花了一段时间才弄清楚,因为 webz 中的示例在提及更改headers以考虑csrf令牌等时有点令人困惑。这是一个例子,我希望它可以帮助别人。

First: the form that goes in your view:

第一:在你看来的形式:

{{ Form::open(['id' => 'testForm']) }}

   <p>{{ Form::label('title', 'Title') }}
   {{ Form::text('title') }}</p>

   <p>{{ Form::label('description', 'Description') }}
   {{ Form::text('description') }}</p>

   <p>{{ Form::submit('Submit') }}</p>

{{ Form::close() }}

Second: write your route in route.php:

第二:写你的路线route.php

Route::post('ad', 'AdController@store');

Third: the Controller:

三:控制器:

public function store()
{

if(Request::ajax()){

    $ad = new ad; 
    $ad -> title = Input::get('title');
    $ad -> description = Input::get('description');
    $ad -> save();

    $response = array(
        'status' => 'success',
        'msg' => 'Option created successfully',
    );

    return Response::json( $response );

    }

}

Fourth: The jquery ajax request:

四:jquery ajax请求:

$('form#testForm').submit(function(e){
  e. preventDefault();


  var str1 = $('input[name="title"]').val();
  var str2 = $('input[name="description"]').val();
  var str3 = $('input[name="_token"]').val();
  var data = {title:str1,description:str2, token:str3};
  //console.log(data);
  var request = $.ajax({
    url: "ad",
    type: "POST",
    data: data ,
    dataType: "html"
  });

  request.done(function( msg ) {
    var response = JSON.parse(msg);
    console.log(response.msg);
  });

  request.fail(function( jqXHR, textStatus ) {
    console.log( "Request failed: " + textStatus );
  });

  });

Thats, it. For protection you can set the Session::token() == Input::get('_token')in the controller as the if check. This is just an example that works fine to get you started. Using absolute URL might be necessary (in that case use http://www.pretty.url/ad) were www.pretty.url is your localhostor local private development url.

就是这样。为了保护,您可以Session::token() == Input::get('_token')在控制器中设置 if 检查。这只是一个可以很好地帮助您入门的示例。如果http://www.pretty.url/adwww.pretty.url 是您localhost或本地的私有开发 url,则可能需要使用绝对 URL(在这种情况下使用)。

回答by jithujose

You've to be able to intercept clicks on the "Show" link. If you make your controller restful, it should be easy to make an ajax request to your controller.

您必须能够拦截对“显示”链接的点击。如果你让你的控制器安静,那么向你的控制器发出 ajax 请求应该很容易。

You've to send an ajax requestwhen the user clickson the Show link.

当用户单击Show 链接时,您必须发送一个ajax 请求

I suggest you to output the results as JSON, so it's pretty easy to later use js to output your results.

我建议您将结果输出为 JSON,以便以后使用 js 输出结果非常容易。