Necesito un ejemplo correcto para envíe y recibí datos de AJAX en Zend Framework 3 -- ajax campo con zend-framework3 camp Relacionados El problema

I need correct example for ajax send and received data in zend framework 3


0
vote

problema

Español

Ejemplo para enviar y recibió datos entre la función AJAX y la acción del controlador en Zend Framework 3

Original en ingles

Example for send and received data between ajax function and action of controller in Zend framework 3

     

Lista de respuestas

1
 
vote
vote
La mejor respuesta
 

Aquí hay un ejemplo simple de una solicitud AJAX usando ZF3. Puede intentarlo con este. En este ejemplo, usaríamos el módulo predeterminado $('#myDiv').animate( { top: "-=20px" }, 300); 99 $('#myDiv').animate( { top: "-=20px" }, 300); 69) de ZF3.

Supongamos que recuperaríamos los datos a través de una llamada AJAX de la siguiente URL.

  add_action( 'pre_get_posts', 'main_query_without_subcategory_posts' );  function main_query_without_subcategory_posts( $query ) {  if ( ! is_admin() && $query->is_main_query() ) {     // Not a query for an admin page.     // It's the main query for a front end page of your site.      if ( is_category() ) {     //Get the current category         $current_category = get_queried_object();         //get the id of the current category         $current_cat_id = $current_category->term_id;          //find the children of current category         $cat_args = array( 'parent'=>$current_category->term_id, 'child_of' => $current_category->term_id, );         $subcategories = get_categories( $cat_args );          //Get a list of subcategory ids, stick a minus sign in front         $subcat_id = array();                  foreach($subcategories as $subcategory) {              $subcat_id[] = " -". $subcategory->term_id;          }          //join them together as a string with a comma seperator                   $excludesubcatlist = join(',', $subcat_id);         //If you have multiple parameters, use $query->set multiple times         $query->set( 'posts_per_page', '10' );         $query->set( 'cat', ''.$current_cat_id.','.$excludesubcatlist.'' );       }     }   } 0  

Vamos a crear un método de acción para la ruta add_action( 'pre_get_posts', 'main_query_without_subcategory_posts' ); function main_query_without_subcategory_posts( $query ) { if ( ! is_admin() && $query->is_main_query() ) { // Not a query for an admin page. // It's the main query for a front end page of your site. if ( is_category() ) { //Get the current category $current_category = get_queried_object(); //get the id of the current category $current_cat_id = $current_category->term_id; //find the children of current category $cat_args = array( 'parent'=>$current_category->term_id, 'child_of' => $current_category->term_id, ); $subcategories = get_categories( $cat_args ); //Get a list of subcategory ids, stick a minus sign in front $subcat_id = array(); foreach($subcategories as $subcategory) { $subcat_id[] = " -". $subcategory->term_id; } //join them together as a string with a comma seperator $excludesubcatlist = join(',', $subcat_id); //If you have multiple parameters, use $query->set multiple times $query->set( 'posts_per_page', '10' ); $query->set( 'cat', ''.$current_cat_id.','.$excludesubcatlist.'' ); } } } 1111 en el add_action( 'pre_get_posts', 'main_query_without_subcategory_posts' ); function main_query_without_subcategory_posts( $query ) { if ( ! is_admin() && $query->is_main_query() ) { // Not a query for an admin page. // It's the main query for a front end page of your site. if ( is_category() ) { //Get the current category $current_category = get_queried_object(); //get the id of the current category $current_cat_id = $current_category->term_id; //find the children of current category $cat_args = array( 'parent'=>$current_category->term_id, 'child_of' => $current_category->term_id, ); $subcategories = get_categories( $cat_args ); //Get a list of subcategory ids, stick a minus sign in front $subcat_id = array(); foreach($subcategories as $subcategory) { $subcat_id[] = " -". $subcategory->term_id; } //join them together as a string with a comma seperator $excludesubcatlist = join(',', $subcat_id); //If you have multiple parameters, use $query->set multiple times $query->set( 'posts_per_page', '10' ); $query->set( 'cat', ''.$current_cat_id.','.$excludesubcatlist.'' ); } } } 2 .

  add_action( 'pre_get_posts', 'main_query_without_subcategory_posts' );  function main_query_without_subcategory_posts( $query ) {  if ( ! is_admin() && $query->is_main_query() ) {     // Not a query for an admin page.     // It's the main query for a front end page of your site.      if ( is_category() ) {     //Get the current category         $current_category = get_queried_object();         //get the id of the current category         $current_cat_id = $current_category->term_id;          //find the children of current category         $cat_args = array( 'parent'=>$current_category->term_id, 'child_of' => $current_category->term_id, );         $subcategories = get_categories( $cat_args );          //Get a list of subcategory ids, stick a minus sign in front         $subcat_id = array();                  foreach($subcategories as $subcategory) {              $subcat_id[] = " -". $subcategory->term_id;          }          //join them together as a string with a comma seperator                   $excludesubcatlist = join(',', $subcat_id);         //If you have multiple parameters, use $query->set multiple times         $query->set( 'posts_per_page', '10' );         $query->set( 'cat', ''.$current_cat_id.','.$excludesubcatlist.'' );       }     }   } 3  

Creamos un método, necesitamos crear una plantilla de vista para ello.

vista / aplicación / índice / title.phtml

  add_action( 'pre_get_posts', 'main_query_without_subcategory_posts' );  function main_query_without_subcategory_posts( $query ) {  if ( ! is_admin() && $query->is_main_query() ) {     // Not a query for an admin page.     // It's the main query for a front end page of your site.      if ( is_category() ) {     //Get the current category         $current_category = get_queried_object();         //get the id of the current category         $current_cat_id = $current_category->term_id;          //find the children of current category         $cat_args = array( 'parent'=>$current_category->term_id, 'child_of' => $current_category->term_id, );         $subcategories = get_categories( $cat_args );          //Get a list of subcategory ids, stick a minus sign in front         $subcat_id = array();                  foreach($subcategories as $subcategory) {              $subcat_id[] = " -". $subcategory->term_id;          }          //join them together as a string with a comma seperator                   $excludesubcatlist = join(',', $subcat_id);         //If you have multiple parameters, use $query->set multiple times         $query->set( 'posts_per_page', '10' );         $query->set( 'cat', ''.$current_cat_id.','.$excludesubcatlist.'' );       }     }   } 4  

Ahora crearíamos otro método de acción en el add_action( 'pre_get_posts', 'main_query_without_subcategory_posts' ); function main_query_without_subcategory_posts( $query ) { if ( ! is_admin() && $query->is_main_query() ) { // Not a query for an admin page. // It's the main query for a front end page of your site. if ( is_category() ) { //Get the current category $current_category = get_queried_object(); //get the id of the current category $current_cat_id = $current_category->term_id; //find the children of current category $cat_args = array( 'parent'=>$current_category->term_id, 'child_of' => $current_category->term_id, ); $subcategories = get_categories( $cat_args ); //Get a list of subcategory ids, stick a minus sign in front $subcat_id = array(); foreach($subcategories as $subcategory) { $subcat_id[] = " -". $subcategory->term_id; } //join them together as a string with a comma seperator $excludesubcatlist = join(',', $subcat_id); //If you have multiple parameters, use $query->set multiple times $query->set( 'posts_per_page', '10' ); $query->set( 'cat', ''.$current_cat_id.','.$excludesubcatlist.'' ); } } } 5 desde donde haríamos la llamada AJAX.

  add_action( 'pre_get_posts', 'main_query_without_subcategory_posts' );  function main_query_without_subcategory_posts( $query ) {  if ( ! is_admin() && $query->is_main_query() ) {     // Not a query for an admin page.     // It's the main query for a front end page of your site.      if ( is_category() ) {     //Get the current category         $current_category = get_queried_object();         //get the id of the current category         $current_cat_id = $current_category->term_id;          //find the children of current category         $cat_args = array( 'parent'=>$current_category->term_id, 'child_of' => $current_category->term_id, );         $subcategories = get_categories( $cat_args );          //Get a list of subcategory ids, stick a minus sign in front         $subcat_id = array();                  foreach($subcategories as $subcategory) {              $subcat_id[] = " -". $subcategory->term_id;          }          //join them together as a string with a comma seperator                   $excludesubcatlist = join(',', $subcat_id);         //If you have multiple parameters, use $query->set multiple times         $query->set( 'posts_per_page', '10' );         $query->set( 'cat', ''.$current_cat_id.','.$excludesubcatlist.'' );       }     }   } 6  

así que hagamos que el método de acción también ...

  add_action( 'pre_get_posts', 'main_query_without_subcategory_posts' );  function main_query_without_subcategory_posts( $query ) {  if ( ! is_admin() && $query->is_main_query() ) {     // Not a query for an admin page.     // It's the main query for a front end page of your site.      if ( is_category() ) {     //Get the current category         $current_category = get_queried_object();         //get the id of the current category         $current_cat_id = $current_category->term_id;          //find the children of current category         $cat_args = array( 'parent'=>$current_category->term_id, 'child_of' => $current_category->term_id, );         $subcategories = get_categories( $cat_args );          //Get a list of subcategory ids, stick a minus sign in front         $subcat_id = array();                  foreach($subcategories as $subcategory) {              $subcat_id[] = " -". $subcategory->term_id;          }          //join them together as a string with a comma seperator                   $excludesubcatlist = join(',', $subcat_id);         //If you have multiple parameters, use $query->set multiple times         $query->set( 'posts_per_page', '10' );         $query->set( 'cat', ''.$current_cat_id.','.$excludesubcatlist.'' );       }     }   } 7  

y la plantilla de la vista sería así

vista / aplicación / índice / text.phtml

  add_action( 'pre_get_posts', 'main_query_without_subcategory_posts' );  function main_query_without_subcategory_posts( $query ) {  if ( ! is_admin() && $query->is_main_query() ) {     // Not a query for an admin page.     // It's the main query for a front end page of your site.      if ( is_category() ) {     //Get the current category         $current_category = get_queried_object();         //get the id of the current category         $current_cat_id = $current_category->term_id;          //find the children of current category         $cat_args = array( 'parent'=>$current_category->term_id, 'child_of' => $current_category->term_id, );         $subcategories = get_categories( $cat_args );          //Get a list of subcategory ids, stick a minus sign in front         $subcat_id = array();                  foreach($subcategories as $subcategory) {              $subcat_id[] = " -". $subcategory->term_id;          }          //join them together as a string with a comma seperator                   $excludesubcatlist = join(',', $subcat_id);         //If you have multiple parameters, use $query->set multiple times         $query->set( 'posts_per_page', '10' );         $query->set( 'cat', ''.$current_cat_id.','.$excludesubcatlist.'' );       }     }   } 8  

Este script necesita la biblioteca JQuery Javascript para hacer la llamada AJAX. Así que asegúrese de que se agregue el script en su vista / diseño / diseño.phtml.

Lo último que necesitamos es configurar las rutas para el add_action( 'pre_get_posts', 'main_query_without_subcategory_posts' ); function main_query_without_subcategory_posts( $query ) { if ( ! is_admin() && $query->is_main_query() ) { // Not a query for an admin page. // It's the main query for a front end page of your site. if ( is_category() ) { //Get the current category $current_category = get_queried_object(); //get the id of the current category $current_cat_id = $current_category->term_id; //find the children of current category $cat_args = array( 'parent'=>$current_category->term_id, 'child_of' => $current_category->term_id, ); $subcategories = get_categories( $cat_args ); //Get a list of subcategory ids, stick a minus sign in front $subcat_id = array(); foreach($subcategories as $subcategory) { $subcat_id[] = " -". $subcategory->term_id; } //join them together as a string with a comma seperator $excludesubcatlist = join(',', $subcat_id); //If you have multiple parameters, use $query->set multiple times $query->set( 'posts_per_page', '10' ); $query->set( 'cat', ''.$current_cat_id.','.$excludesubcatlist.'' ); } } } 9 y <?php while (have_posts() ) : the_post(); ?> <h2><?php the_title();?></h2> <p> etc....</p> <?php endwhile;?> 0 . Vamos a agregar esas dos rutas a la sección de ruta del módulo / aplicación / config / module.config.php

  <?php  while (have_posts() ) : the_post(); ?>      <h2><?php the_title();?></h2>      <p> etc....</p>  <?php endwhile;?> 1  

¡Háganos saber si te hace feliz!

 

Here is a simple example of an ajax request using ZF3. You may give a try with this one. In this example we would use ZF3's default Application module.

Lets assume we would retrieve data via a ajax call from the following url.

http://yoursite.com/title 

Lets create an action method for the title route in the IndexController.

public function titleAction() {     // Initialize view     $view = new ViewModel();      // Checks if this is a Javascript request     $xmlHttpRequst = $this->getRequest()->isXmlHttpRequest();      if (! $xmlHttpRequst) {         die('Bad request');     }      /**      * Here we may pull data from database but for tests      * here we make an array of titles for the view      */     $titles = [];     for ($i = 0; $i < 10; $i++) {         $titles[] = "Lorem ipsum dolor {$i}";     }      // Set data to be used in the view     $view->setVariable('titles', $titles);      /**      * Tell the renderer not to show the layout      * by setting setTerminal to true      */     $view->setTerminal(true);      return $view;         }  

We created a method, we need creating a view template for it.

view/application/index/title.phtml

<?php  foreach ($titles as $title) {     echo '<h2>' . $title . '</h2>'; } 

Now we would create another action method in the IndexController from where we would make the ajax call.

http://yoursite.com/text 

So lets make that action method too...

public function textAction() {     return new ViewModel(); } 

and view template would be like so

view/application/index/text.phtml

<h1>Handling ajax request</h1>  <button onclick="showTitle()">Show Title</button>  <div id="box"></div>  <?php     // Set url        $url = $this->serverUrl('/title'); // http://yoursite.com/title      // This is for the "url" catch     echo "<script>" . PHP_EOL;     echo "\tvar url = '{$url}';" . PHP_EOL;     echo "</script>" . PHP_EOL; ?>  <script>     function showTitle() {         $.get(url, function(data){             $('#box').html(data);         })         .done(function(){             console.log('Done!');         })         .fail(function(){             console.log('Failed!');         });           } </script> 

This script needs jQuery Javascript library to make the ajax call. So make sure that script is added in your view/layout/layout.phtml.

The last thing we need is to set up routes for the /title and /text. Lets add those two routes to the route section of module/Application/config/module.config.php

'title' => [     'type' => Literal::class,     'options' => [         'route' => '/title',         'defaults' => [             'controller' => Controller\IndexController::class,             'action' => 'title',         ],     ], ], 'text' => [     'type' => Literal::class,     'options' => [         'route' => '/text',         'defaults' => [             'controller' => Controller\IndexController::class,             'action' => 'text',         ],     ], ], 

Let us know if it makes you happy!

 
 
 
 

Relacionados problema

0  Agregar mensaje a la carpeta IMAP usando ZF3  ( Adding message to imap folder using zf3 ) 
Estoy tratando de agregar un nuevo mensaje a la carpeta IMAP usando Zend Framework 3. El código que utilizo es el siguiente: ... $draftMessage = new endMa...

-1  Creación del ayudante (ayudante) en Zend Framework 3 (es imposible)  ( Creation of the helper helper in zend framework 3 is impossible ) 
Estoy creando clase en / módulo / aplicación / src / vista / ayudante / mensajes Código: <?php namespace ApplicationViewHelper; use ZendViewHelperAbstrac...

1  Zend Framework 3 + Doctrine 2 Generar entidades  ( Zend framework 3 doctrine 2 generate entities ) 
¿Cómo configurar el proyecto ZF3 para poder usar el comando generate-entidades de las herramientas de Doctrine Orm? I Uso Application Entity Namespace para...

1  PHP 7.3, Zend 3 Framework - Error de conexión SQLite PDO [DUPLICADO]  ( Php 7 3 zend 3 framework sqlite pdo connection error ) 
Esta pregunta ya tiene respuestas aquí : ¿Cómo habilitar SQLite3 para PHP? ...

3  Doctrine2 Múltiples DB Conectar en ZF3?  ( Doctrine2 multiple db connect in zf3 ) 
Usé Doctrine2 en ZF3, mientras que conecta un error de DB causado por DB. Luego, sigue mi configuración en global.php _[2018-07-05T13:59:05,753][INFO ][log...

1  Recuperando y mostrando comentarios de YouTube API a través de Zend Framework 3  ( Retrieving and displaying comments from youtube api through zend framework 3 ) 
Necesito mostrar comentarios de un video dado que se mostrará dentro de Zend Framework3. Creo que estoy obteniendo la respuesta adecuada de YouTube API para...

0  ZF3 - ¿Cómo extiende un controlador desde un marco en un directorio de proveedores?  ( Zf3 how to extends a controller from a framework in a vendor directory ) 
Estoy trabajando con ZendFrameWork3 para un proyecto. Tengo un módulo que funciona (Por ejemplo: MyProject / Module / Mymodule). Todo lo que está funcionando,...

2  ¿Cómo hacer que la solicitud HTTP de Reactjs?  ( How to make http request from reactjs ) 
Estoy usando Reacc JS como Front End y ZF3 como un backend en mi aplicación de ToDO. Puse toda mi carpeta de reacción y archivos en la carpeta pública de Zend...

0  ZF3: Los controladores con rutas infantiles no funcionan  ( Zf3 controllers with child routes doesnt work ) 
Soy desarrollador ZF2 y estoy migrando a ZF3 y estoy teniendo problemas con algunos controladores. Por ejemplo, tengo esta URL: http: // localhost / admin ...

1  Validador personalizado no encontrado por ValidatorpluginManager  ( Custom validator not found by validatorpluginmanager ) 
Estoy luchando con hacer que mi validador personalizado funcione. La cosa es que tengo un elemento de formulario personalizado que utiliza un validador person...




© 2022 respuesta.top Reservados todos los derechos. Centro de preguntas y respuestas reservados todos los derechos