【问题标题】:alert success bootstrap for json_encode responsejson_encode 响应的警报成功引导
【发布时间】:2020-04-20 09:33:40
【问题描述】:

我有 2 个条件像这样以 json 格式返回

public funtion do_upload{
//1st
return json_encode(['upload_success' => 'Successfully import ' . $count_validEntries . ' document]);

//2nd
return json_encode(['upload_error' => 'Your document is not valid, at row '. $implode_err. 'Please use given data']);
}

我的 Ajax 调用

  $("#upload_btn").on('click', function(){
    var mydata = new FormData(document.getElementById("form_upload"));
    $.ajax({
      type : "POST",
      data: mydata,
      contentType: false,
      dataType : "json",
      url : "<?php echo base_url();?>/C_MRCR_A/do_upload",
      cache: false,
      processData: false,
      beforeSend:function(){
      },
      success:function(response){
        console.log('succ ',response);
      },
      error:function(xhr, status, error){
      },
      complete:function(){
        // do nothing for now
      }
    });
  });

如果'upload_success' 我想让alert 成功,如果'upload_error' 使用上面的响应,我想警告错误?还是有其他方法?

【问题讨论】:

  • 您是否将此响应发送到 Ajax 调用?
  • @AlokMali 对,我已经编辑了我的问题
  • 您希望在 HTML 中的什么位置显示警报?
  • 当我点击upload_btn后,如果这就是你的意思

标签: php json jsonresponse


【解决方案1】:

您需要在成功函数中应用条件。如下 -

success:function(response){
    //console.log('succ ',response);
    if(response.upload_success){
      $('#response').html('<div class="alert alert-success" role="alert"> T'+response.upload_success+' </div>');
    } else if(response.upload_error){
      $('#response').html('<div class="alert alert-success" role="alert"> '+response.upload_error+' </div>');
    }
}

在您的 HTML 中创建一个 div 以显示响应。

<div id="response"></div>

您可以随心所欲地附加/显示此响应。

【讨论】:

  • 已申请。但为什么不显示警报?我将&lt;div id="response"&gt;&lt;/div&gt; 放在模态之外
  • 将 div 放入模型中。请确保它的 id 在您的 HTML 文件中是唯一的
  • 把 div 放在模态框里,id 它是独一无二的。仍然没有出现任何警报。我试图console.log(response.upload_success) 它显示undifined。但为什么呢?
  • 您需要在服务器端回显您的结果而不是返回。在此更改之后,请在您的成功函数中控制台响应。
  • 是的,这样做是为了喜欢这个echo json_encode(['upload_success' ...,但我的 console.log 没有得到任何东西,因为它总是在 ajax 中转到 error:function(xhr, status, error) 而不是success:function(response)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-10
  • 2014-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-14
相关资源
最近更新 更多