使用 ajax 和 laravel 从数据库中检索数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36521573/
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 13:34:51  来源:igfitidea点击:

Retrieve data from database using ajax with laravel

ajaxlaravel

提问by PlayHardGoPro

I'm able to select a value from database and throw it inside a <div>.
My problem is, I don't know how to do so and follow the MVCrules, as I'm using Laravelframework.

我可以从数据库中选择一个值并将其放入<div>.
我的问题是,我不知道该怎么做并遵守MVC规则,因为我正在使用Laravel框架。

Here is what I've done so far:

这是我到目前为止所做的:

Index.php

索引.php

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="https://code.jquery.com/jquery-2.2.3.min.js"   integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo="   crossorigin="anonymous"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="script.js"></script>
</head>
<body>
    <div id="wrapper">
        <input type="button" id="btn" value="Click Me :)"></input>
    </div>
</body>
</html>  

Ajax.php

ajax.php

<?php

include ('db.php');

$pdo = connect();

$dados = $pdo->prepare("SELECT field FROM table WHERE id = ?");
$dados->execute(array("2"));
$usr = $dados->fetch(PDO::FETCH_ASSOC);


echo "<p> Nome:" .$usr["nome"]. "</p>"; //Teste  

Script.js

脚本.js

$(document).ready(function(){
    $('#btn').click(function(){
        $.ajax({
        url: "ajax.php",
        type: "GET",
        dataType: "html", //expected return type        
        success: function(response){
            $('#calendario').fullCalendar(
            'renderEvent',
            {
                title: 'Novo evento',
                start: '2016-04-06T08:00:00', // I need to put the data here
                end:'2016-04-06T10:30:00'    // And here aswell
            }
        );
        }

    })

    });
});

I made this as a test, and it's working... How may I do the same using Laravel MVC? Here I had to create a custom php file (ajax.php) only to make the select. Is there a way to do the same thing using my Controller /Model?

我做了这个作为测试,它正在工作......我如何使用它做同样的事情Laravel MVC?在这里,我必须创建一个自定义的 php 文件 (ajax.php) 才能进行选择。有没有办法用 my 做同样的事情Controller /Model

回答by Patrick Lewis

Yes. What you would do is have the URL point to a route (URL) that you specify. You would specify the route in app/Http/routes.php like so:

是的。您要做的是让 URL 指向您指定的路由 (URL)。您可以在 app/Http/routes.php 中指定路由,如下所示:

    // Perform some action
    Route::get('/whatever/url/you/like', 'SomeController@someAction');

This will look for a "GET" method call, which means you can test it from the browser as well. The first parameter is the URL you want to use, while the second parameter is a Controller, the @ sign, then the public function you want called.

这将查找“GET”方法调用,这意味着您也可以从浏览器中对其进行测试。第一个参数是您要使用的 URL,而第二个参数是 Controller、@ 符号,然后是您要调用的公共函数。

In the controller class you create, you would return an array with the data you want returned. Laravel automatically converts that array into JSON for your consumption by default.

在您创建的控制器类中,您将返回一个包含您想要返回的数据的数组。默认情况下,Laravel 会自动将该数组转换为 JSON 以供您使用。

If you're asking about how to go about separating the code (what should be in the controller and what should be in the model), then you can use the artisan command at the command line to have Laravel automatically create a blank controller class for you with public functions for common actions on an object:

如果您询问如何分离代码(控制器中应该有什么,模型中应该有什么),那么您可以在命令行中使用 artisan 命令让 Laravel 自动创建一个空白的控制器类您可以使用公共函数对对象进行常见操作:

php artisan make:controller PhotoController

More info can be found in Laravel's documentation. If you limit the code in the controller to actions done on an object created using the Model class, that will go a long way in getting you started. Hope this helps!

更多信息可以在 Laravel 的文档中找到。如果您将控制器中的代码限制为对使用 Model 类创建的对象执行的操作,这将对您入门大有帮助。希望这可以帮助!

If entering the URL for the AJAX call in your browser returns some JSON, then you're on the right track. From the JavaScript making the call, the "response" variable should contain that data. If you need analyze it, use Chrome DevTools and add a checkpoint so that you can analyze exactly is returned in that variable. Another alternative is to use console.log to print that data to the browser's console.

如果在浏览器中输入 AJAX 调用的 URL 会返回一些 JSON,那么您就在正确的轨道上。从进行调用的 JavaScript 来看,“响应”变量应该包含该数据。如果您需要分析它,请使用 Chrome DevTools 并添加一个检查点,以便您可以准确分析该变量中返回的值。另一种选择是使用 console.log 将该数据打印到浏览器的控制台。

回答by Achraf Khouadja

Controller

控制器

public function testajax($id) {

$test = table::findorfail($id)->toarray();
return response()->json($test);
}

javascript

javascript

$(document).ready(function()
                      {
                       $(document).on('submit', '#reg-form', function()
                       {

                      var data = $(this).find("#post_id").val();
                        $.ajax({
                        type : 'GET',
                        url  : {{url("/ajax")}}',
                       data: data,
                       success: function(data) {
                          console.log(data);
                      },
                            error :  function(data)
                            {
                                alert("error");
                            }
                        });
                        return false;
                       });
                      });

routes file

路由文件

Route::get('/ajax/{id}', 'Contoller@testajax');

this code dosent realy work but this is how its done

这段代码确实有效,但这就是它的完成方式