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

时间:2021-12-14 01:38:22

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 MVC rules, as I'm using Laravel framework.

我可以从数据库中选择一个值并将其放入

中。我的问题是,我不知道如何这么做并遵循MVC规则,因为我正在使用Laravel框架。

Here is what I've done so far:

以下是我至今所做的:

Index.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

<?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

$(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)来进行选择。有办法用我的控制器/模型做同样的事情吗?

2 个解决方案

#1


2  

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/路由中指定路由。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,而第二个参数是控制器@符号,然后是要调用的公共函数。

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:

如果你询问如何分离的代码(应该是在控制器和应该在模型中),那么您可以使用工匠命令在命令行有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的文档中找到。如果您将控制器中的代码限制为使用模型类创建的对象上的操作,那么将会在启动过程中进行很长一段时间。希望这可以帮助!

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并添加一个检查点,这样您就可以在该变量中精确地分析返回。另一种选择是使用控制台。登录以将数据打印到浏览器的控制台。

#2


1  

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

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

#1


2  

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/路由中指定路由。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,而第二个参数是控制器@符号,然后是要调用的公共函数。

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:

如果你询问如何分离的代码(应该是在控制器和应该在模型中),那么您可以使用工匠命令在命令行有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的文档中找到。如果您将控制器中的代码限制为使用模型类创建的对象上的操作,那么将会在启动过程中进行很长一段时间。希望这可以帮助!

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并添加一个检查点,这样您就可以在该变量中精确地分析返回。另一种选择是使用控制台。登录以将数据打印到浏览器的控制台。

#2


1  

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

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