UserFrosting:传递参数,异步数据获取 [英] Userfrosting: Passing Params, Async Data Fetching

查看:216
本文介绍了UserFrosting:传递参数,异步数据获取的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对UF很新,我正在开发基于所包含工具的网络工具。我已经仔细阅读了所有的教程,也大部分了解PHP,Twig,Slim和JQuery之间的基本工作流程。即使我不是所有这些技术的专业人员,因此我有两个问题,这些问题让我有一点能够发现我想要实现的内容。如果问题有些愚蠢,请不要怪我。



1)什么是参数/预期方式将参数传回给在使用JQuery重新加载页面时,以及在将某些数据POST到端点之后的初始页面。为了更清楚这里有一个例子:




  • 基于Twig的网站加载

  • 一些数据被POST到一个端点并进行处理(包括重新加载初始页面所需的参数)

  • JQuery启动路由(重新加载)

  • 初始站点根据twig重新加载(这里我需要参数)



它不是全局必需参数,所以我猜会话变量不会一个充足的选择。另外将它放在url路径(不是查询参数)也不是正确的解决方案,因为参数只与视图有关,而不是直接与在此路由中处理的对象相关。



目前我使用的是一个查询参数,我通过URL重新加载。有没有更好的处理所需功能的方法?



  statusText,jqXHR){var cSelect = $('#input_group')。val(); window.location ={{site.uri.public}} / states?c =+ cSelect; }  



2)第二个问题有点更加漫长我不完全知道如何做到这一点。根据用户交互,在页面上获取数据的最佳方法是什么?选择一个选择标签中的一个选项,我想依次更新其他选择标签中的选项元素。



如果我错了,请更正我的想法。我将建立一个JQuery例程,对第一个选择标签的更改做出反应,访问特定的路径以获取数据,并使用新的获取的数据交换现有的选项。这是正确的方法吗?如果有人可以为JQuery附加一些基本代码,但特别是对于Controller,这样我可以正确地将信息从php传回到Javascript(响应的格式?json?),这将使我真的很开心。重新加载一个简单的字符串就足够了,我可以想出的一切,只需要一些基本的信息,如何做到这一点。



我知道如何做这件事情,但是我想根据包含UF的工具正确地做到这一点。因此,我的问题,我也认为这将有助于其他新人UF和其他工具。

解决方案

解决方案:Thx Alex



1)对于我的应用场景=> 存储GUI状态,HTML5 本地存储似乎是完美的解决方案(sessionStorage,localStorage)。但是,如果要保留旧版或在服务器端重新加载期间需要传递的信息,则定义查询参数将成为大多数HTTP GET请求的首选选项。



2)我用AJAX和一个UF JSON端点播放了一些。所产生的解决方案应该有助于实现一个例程,允许异步重新加载数据并使用JQuery将其打印到DOM(在下面的表格中)。



这里视图的示例代码(yourview.twig):

  var $ selC = $(#input_group); //例如。 < select> -tag 
$ selC.on('change',function(){
var $ tableBody = $(#your_table_body);

$ .ajax ({
url:'{{site.uri.public}} / json / yourendpoint',
type:GET,
dataType:json,
success: function(data,textStatus,jqXHR){
renderJsonToTable(data);
alert(jqXHR.status);
},
error:function(jqXHR,textStatus,errorThrown){
alert(jqXHR.status);
}
});

函数renderJsonToTable(data){
$ tableBody.empty();
var htmlBody = $ .map(data,function(item,i){
return&l t; tr>< th scope = \row\>+ item.id +< / th>< td>+ item.name +< / td>< / tr> ;;
})。join();

$ tableBody.append(htmlBody);
}

});

和php端点实现(JsonController.php):

  class JsonController extends \UserFrosting\BaseController {

private static $ content_type ='Content-Type';
private static $ content_json ='application / json';

public function __construct($ app){
$ this-> _app = $ app;
}

public function getElements(){

$ responseContent ='';
$ response = $ this-> _app->响应;

//访问控制页
if(!$ this-> _app-> user-> checkAccess('uri_access_right')){
$ responseContent =拒绝访问';
$ response-> setStatus(403);
} else {
$ responseContent = Elements :: get();
$ response-> setStatus(200);
}

$ response [self :: $ content_type] = self :: $ content_json;
$ response-> body(json_encode($ responseContent));

}
}

最后路由(index.php ):$($ / $)

  $ app-> get('/ json / yourendpoint /? {
$ controller = new UF\JsonController($ app);
return $ controller-> getElements();
});


I'm quite new to UF and I'm developing a web tool based on the included tooling. I already read all the tutorials carefully and also mostly understand the basic workflows between PHP, Twig, Slim and JQuery. Even though I'm not a professional in all of these technologies and therefore I have two questions, which hold me a little back on developting the stuff that I want to achieve. Please don't blame me if the questions are some kind of stupid.

1.) What is the "right" / "expected" way to pass parameters back to an initial page during reloading the page with JQuery and after POSTing some data to an endpoint. To make it more clear here a little example:

  • Site based on Twig is loaded
  • Some data is POSTed to an endpoint and processed (including a parameter needed after reloading the inital page)
  • JQuery initiates the routing (reloading)
  • initial Site is reloaded based on twig (here I need the parameter)

It is no global required parameter so i guess a session variable would not be an adequate option. Also putting it in the url path (not query param) would also not be the proper solution because the parameter is only related to the view and not directly to the object processed in this route.

Currently I use a query parameter, which I pass with the URL on reload. Is there a better way of handling the needed funcionality?

function(data, statusText, jqXHR) {
    var cSelect = $('#input_group').val();
    window.location="{{site.uri.public}}/states?c=" + cSelect;  
}

2.) The second question is a little more diffuse because I don't exactly know how to do this. What would be the best way of fetching data on a page in dependence of an user interaction e.g. an option in a select-tag is chosen and I want to update the option elements in an other select-tag in dependence.

Please correct my thoughts if I'm wrong. I would build up a JQuery routine which reacts on changes of the first select-tag, accesses a specific route to fetch the data and exchange the existing option's with the new fetched data. Would this be the correct approach? It would make me really really happy if someone can attach some basic code for the JQuery but especially for the Controller and in which way I can correctly pass back the information from php to Javascript (format of the response? json?). Reloading a simple string would be enough, everything else I can figure out myself just need some kind of basic information how to do this right.

I know how to do both of this things, but I want to do it correctly based on the UF included tooling. Therefore my question and I also think this would help other people who are new to UF and the included tools.

解决方案

Solution: Thx to Alex

1.) For my application scenario => "storing GUI states", the HTML5 local storage seems the perfect solution (sessionStorage, localStorage). But if you want preserve legacy or need the passed information during server-side reloading - defining query parameters would be the preferred option for most of the HTTP GET requests.

2.) I played a little with AJAX and an UF JSON endpoint. The resulting solution should help on implementing a routine which allows the async reloading of data and printing it with JQuery to the DOM (in the case below a table body).

Here the example code for the view (yourview.twig):

                var $selC = $("#input_group"); //e.g. <select>-tag
                $selC.on('change', function() {     
                    var $tableBody =  $("#your_table_body");

                    $.ajax({
                        url: '{{site.uri.public}}/json/yourendpoint',
                        type: "GET",
                        dataType: "json",
                        success: function(data, textStatus, jqXHR) {
                            renderJsonToTable(data);
                            alert(jqXHR.status);
                        },
                        error: function(jqXHR, textStatus, errorThrown) {
                            alert(jqXHR.status);
                        }
                    });

                    function renderJsonToTable(data){
                        $tableBody.empty();
                        var htmlBody = $.map(data, function (item, i) {
                            return "<tr><th scope=\"row\">" + item.id + "</th><td>" + item.name + "</td></tr>";
                        }).join("");

                        $tableBody.append(htmlBody);
                    }

                });

and for the php endpoint implementation (JsonController.php):

    class JsonController extends \UserFrosting\BaseController {

    private static $content_type = 'Content-Type';
    private static $content_json = 'application/json';

    public function __construct($app){
        $this->_app = $app;
    }

    public function getElements(){

         $responseContent = '';
         $response = $this->_app->response;

         // Access-controlled page
         if (!$this->_app->user->checkAccess('uri_access_right')){
            $responseContent = 'Access Denied';
            $response->setStatus(403);
         }else{
             $responseContent = Elements::get();
             $response->setStatus(200);
         }

        $response[self::$content_type] = self::$content_json;
        $response->body( json_encode($responseContent) );

    }
}

Finally the routing (index.php):

$app->get('/json/yourendpoint/?', function () use ($app) {
    $controller = new UF\JsonController($app);
    return $controller->getElements();
});

这篇关于UserFrosting:传递参数,异步数据获取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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