【问题标题】:Return a view with data from ajax使用来自 ajax 的数据返回视图
【发布时间】:2020-05-28 16:54:07
【问题描述】:

当从控制器(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);
}

}

【问题讨论】:

  • 尝试直接加载视图 $this->load->view('Administracion/Propiedades/propiedades_form_fotos',$data);
  • 加载资源失败:服务器响应状态为 500 (Internal Server Error) whit $this->load->view('Administracion/Propiedades/propiedades_form_fotos',$data);这是 CI4 而不是 CI3

标签: ajax codeigniter-4


【解决方案1】:

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

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

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

【讨论】:

  • 'echo' 是同样的错误。这是我第一次写。我确认数组 $data y ok 并且这个相同的视图在其他控制器中也可以,而不是从 ajax 调用。仅在从 ajax 调用此控制器时发生。
  • 您能提供给我们您的 http 500 错误消息吗?看起来您的问题不在您在此处提供的代码范围内。可能是您的 $files 为空或您的视图中有错误。
  • 你是对的!!!问题出在视图中。我找到了。坦克
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-16
  • 1970-01-01
相关资源
最近更新 更多