首页 > 解决方案 > 使用来自 ajax 的数据返回视图

问题描述

将带有数据的视图从控制器(Codeigniter 4)返回到 ajax 函数时出现错误 500:

在 Codeigniter 3 中没有这个问题,当 $this->load->view('some'); 但联合国 CI4 不使用这种方法来显示视图。

在 Codeigniter 4 中:

JS:

<script>

function insertFotosNew(url){
    var form = document.querySelector('#new-fotos-form');
    var fd = new FormData(form);

    $.ajax({
        type: "POST",
        url: '<?=base_url('subir_fotos')?>',
        data: fd,
        contentType: false,
        processData: false,
        success: function (resultado) {
            console.log(resultado);
            $('#card-fotos').html(resultado);


        },
        error: function (resultado) {
            alert('Se ha producido un error al conectar con el servidor.');
        }
    });
 }

控制器:

/**
 * @return View
 */
public function run(){
    $todo       = $this->request->getPost();
    $files      = $this->request->getFiles();

    $data = array();

    if(count($files) > 0) {
        $this->respuesta = $this->propiedadNewFotoUpload($todo['id_producto'], $files);
        $data['fotos'] =  $this->productosFotosRepository->getProductoFotos($todo['id_producto']);
    } else  {
        $this->respuesta->mensaje = 'No hay ficheros para subir';
        $this->respuesta->estado = EXIT_ERROR;
    }

    //return json_encode($this->respuesta);
    return view('Administracion/Propiedades/propiedades_form_fotos',$data);
}

}

标签: ajaxcodeigniter-4

解决方案


你必须回应你的观点,而不是返回它。

 echo view('Administracion/Propiedades/propiedades_form_fotos',$data);

去查看文档,CI4 的文档非常好。https://codeigniter.com/user_guide/general/common_functions.html#view


推荐阅读