Ho un problema con WordPress e Ajax.

Questa è la mia parte JavaScript (lho tagliata un po ):

var posts = $.ajax({ type: "POST", url: ajaxurl, async: false, dataType: "json", data: { action: "myAjaxFunc" }, done: function(response) { return response; } }).responseText; $.each(posts, function() { $("#someSelect").append( $("<option</option>").text(this.name).val(this.id) ); }); 

Il mio codice PHP è il seguente:

function myAjaxFunc() { $posts = get_posts( array( "posts_per_page" => -1, "orderby" => "title", "order" => "ASC", "post_type" => "my-post-type", "post_status" => array( "publish", "draft" ) ) ); $list = array(); foreach ( $posts as $post ) { $list[] = array( "id" => $post->ID, "name" => $post->post_title, "link" => get_permalink( $post->ID ), ); } header("Content-type: application/json"); echo json_encode( $list ); die; } add_action( "wp_ajax_nopriv_myAjaxFunc", "myAjaxFunc" ); add_action( "wp_ajax_myAjaxFunc", "myAjaxFunc" ); 

Lo script riceve la risposta Ajax da admin-ajax. Purtroppo la console genera un errore quando arriva allistruzione each nel codice JavaScript … dice:

"Uncaught TypeError: Cannot use "in" operator to search for "4" in Array". 

Se faccio un console.log dei miei “post” var ottengo una stringa “Array”. Non importa come passo la variabile $list in PHP, restituirà sempre una stringa. La query restituisce post altrove, quindi “non è vuota. Ho provato senza json_encode, con e senza dichiarazione di intestazione, utilizzando wp_send_json(), inserendo ob_clean() prima di echeggiare larray, inserire larray in un array … Ma entra sempre in ajax come stringa Array e each non possono scorrere.

Dovrebbe essere una cosa molto semplice e non riesco a “capire perché” non funziona. Non ho altri errori o avvisi JavaScript o PHP e tutto il resto funziona correttamente.

Commenti

  • Cosa vedi quando vai a example.com/wp-admin/admin-ajax.php?action=myAjaxFunc
  • Qualche progresso sulla tua domanda? Potresti ricontattarmi?
  • oh … questo è di 5 mesi fa … ho risposto alla mia stessa domanda tra laltro il giorno dopo lho postata, usando bit di risposta BODA82 – I appena ' non lha contrassegnata come risposta corretta; @toscho ha aggiunto il suo seguito molto più tardi ieri, posso ' verificare se anche la sua risposta è buona adesso, ha senso però

risposta

BODA82 “risposta ha aiutato, ma alla fine ho capito che avrei dovuto sostituire responseText con il metodo responseJSON nel mio codice JavaScript. Nellesempio seguente stavo memorizzando i risultati della risposta Ajax in una variabile. “Non sapevo” cera un metodo specifico per ottenere la risposta in JSON. In questo modo loggetto / array con get_posts() risultati viene restituito correttamente e non come stringa:

posts = $.ajax({ type: "GET", url: ajaxurl, async: false, dataType: "json", data: { action : "getHotelsList" }, done: function(results) { // Uhm, maybe I don"t even need this? JSON.parse(results); return results; }, fail: function( jqXHR, textStatus, errorThrown ) { console.log( "Could not get posts, server response: " + textStatus + ": " + errorThrown ); } }).responseJSON; // <-- this instead of .responseText 

Nota per me stesso, ma anche consiglio generale: se non puoi “aggiustare qualcosa la sera” è un segno che dovresti andare a letto, leggere un libro e contare le stelle. Una risposta verrà trovata la mattina successiva, prima è meglio è: D

Risposta

Ci sei quasi con la tua funzione PHP. Non è necessario impostare lintestazione. (Modifica: inoltre, supponendo che get_posts() stia effettivamente restituendo risultati.)

function myAjaxFunc() { $posts = get_posts( array( "posts_per_page" => -1, "orderby" => "title", "order" => "ASC", "post_type" => "my-post-type", "post_status" => array( "publish", "draft" ) ) ); $list = array(); foreach ( $posts as $post ) { $list[] = array( "id" => $post->ID, "name" => $post->post_title, "link" => get_permalink( $post->ID ), ); } echo json_encode( $list ); die; } add_action( "wp_ajax_nopriv_myAjaxFunc", "myAjaxFunc" ); add_action( "wp_ajax_myAjaxFunc", "myAjaxFunc" ); 

E il tuo Javascript:

$.ajax({ url: "<?php bloginfo("url"); ?>/wp-admin/admin-ajax.php", type: "POST", data: "action=myAjaxFunc", success: function(results) { var posts = JSON.parse(results); console.log(results); $.each(posts, function() { $("#someSelect").append( $("<option></option>").text(this.name).val(this.id) ); }); }, error: function() { console.log("Cannot retrieve data."); } }); 

Commenti

  • Quando salvi alcuni dati utilizzando JSON.stringify () e poi devi leggerli in php. Il codice seguente ha funzionato per me. json_decode (html_entity_decode (stripeslashes ($ jsonString)));

Risposta

Cè una via duscita. Utilizza complete invece di success o done:

posts = $.ajax({ type: "GET", url: ajaxurl, async: false, dataType: "json", data: { action : "getHotelsList" }, complete: function(results) { 

E prova a rimuovere async:false se il problema persiste.

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *