Ajax получает undefined хорошо отформатированный JSON - PullRequest
0 голосов
/ 05 ноября 2018

Я прочитал большинство записей здесь, ссылающихся на "ajax response undefined", но ни одна из них не работала для меня, или они не были связаны. Я надеюсь не создавать дубликат здесь. Здесь идет вопрос.

У меня хорошо отформатированный JSON. Я спрашиваю php, используя Postman, и Json появляется так, как должно. Я пробовал онлайн-инструменты для проверки целостности Json, и это тоже хорошо. Однако, когда дело доходит до ответа ajax, он автоматически не определен. Весь ответ не определен. Вот код.

Php:

    require_once dirname($_SERVER['DOCUMENT_ROOT']) . '/new/config/config.inc.php';
require_once dirname($_SERVER['DOCUMENT_ROOT']) . '/new/init.php';
require 'producto.php';
require 'Conjunto.php';
$array_referencias = json_decode(stripslashes($_POST['seleccionProductos']));
$imagenes_principales = [
    "jardin.jpg",
    "ceramicas1.jpg"
];
$host_name = 'xx';
$database = 'xx';
$user_name = 'xx';
$password = 'xx';

$conn = mysqli_connect($host_name, $user_name, $password, $database);
if (mysqli_connect_errno()) {
    die("Se ha produción un error de conexión SQL: " . mysqli_connect_error());
}
$id_got = array();
$x = 0;
while ($array_referencias[$x] != null) {
    $y = 0;
    while ($array_referencias[$x][$y] != null) {
        $current_ref = $array_referencias[$x][$y];
        $sql = mysqli_query($conn, "SELECT p.id_product FROM ps_product p where p.reference = '$current_ref'");
        foreach (mysqli_fetch_assoc($sql) as $key => $value) {
            $id_got[$x][$y] = $value;
        }
        $y++;
    }
    $x++;
}
$conn->close();
$conjuntos = array();
$n = 0;
while ($id_got[$n] != null) {
    $o = 0;
    $unidad_prod = array();
    while ($id_got[$n][$o] != null) {
        $id_a_usar = $id_got[$n][$o];
        $id_lang = Context::getContext()->language->id;
        $product = new Product($id_a_usar, false, $id_lang);
        $img = $product->getCover($product->id);
        $image_type = 'small_default'; //Mirar el ftp para ver otros tipos
        $producto = new producto();
        $producto->setNombre(strtoupper($product->name));
        $producto->setPrecio($product->price);
        $producto->setImagen($link->getImageLink(isset($product->link_rewrite) ? $product->link_rewrite : $product->name, (int)$img['id_image'], $image_type));
        $producto->setUrl(Context::getContext()->link->getProductLink($id_a_usar));
        $unidad_prod[] = $producto;
        $o++;
    }
    $conjunto = new Conjunto();
    $conjunto->setImagenprincipal($imagenes_principales[$n]);
    $conjunto->setProductos($unidad_prod);
    $conjuntos[] = $conjunto;
    $n++;
}
$res = json_encode($conjuntos);
echo $res;

JS:

 function request() {
     var refs_en_foto1=[10078,28352,32704,28300,14569,4161,28306,18818,3160,8435,8438,8436,21016,8437,19568,15365,31963,20145,40381,19961,40380,36001];
     var refs_en_foto2=[15365,31963,20145];
     var referencias = [refs_en_foto1,refs_en_foto2];
     var contenidohtml="";
     var x,i=0,y=0;

     for (y in referencias){
         var jsonString = JSON.stringify(referencias[y]);
         jQuery.ajax({
             type: "POST",
             url: 'gallery_connect.php',
             dataType: 'json',
             data: {seleccionProductos: jsonString },
             error: function(xhr, status, error) {
                 console.log("Se produjo el siguiente error: "+error);
             },
             success: function (response) {
**Code doesn't work from here, response is fully 'undefined'**
                    contenidohtml+="<div class='galeria'><div class='contenedor_izq'><img src='"+response[0].imagenprincipal+
                    "'/></div><div class='contenedor_der'>";
                    for(x in response) {
                        contenidohtml+="<div class='caja_articulo'><div class='imagen_articulo'><img id='img1' src='"+response[0].productos[0].imagen+
                            "'/></div><div class='filas_texto'>"+response[0].productos[0].nombre+"</div>";
                        contenidohtml+="<div class='filas_texto botongaleria noselect'><a href='"+response[0].productos[0].url+"'>VER PRODUCTO</a></div></div>"
                         }
                    contenidohtml+="</div></div>";
             }
         });
         y++;
         i++;
     }
     document.getElementById("foto1").innerHTML = contenidohtml;
 }

Ошибка:

Uncaught TypeError: Невозможно прочитать свойство 'imagenprincipal' из неопределено в Object.success (custom.js: 28) в u (jquery.min.js: 2) в Object.fireWith [as resolWith] (jquery.min.js: 2) при k (jquery.min.js: 2) в XMLHttpRequest. (jquery.min.js: 2)

...