duanfei8897 2012-11-13 07:32
浏览 49
已采纳

Codeigniter:如何在提交ajax表单后向用户返回成功/失败消息

I'm starting to get the hang of Codeigniter, but apparently am missing something here.

I'm not sure how to return data to the user after an ajax form submission. Here are the relevant bits of my code, with the question inside:

View:

if (confirm("Are you sure?"))
    {
        var form_data = $('form').serialize();

        $.post("<?php echo site_url();?>" + "/products/update_multiple", (form_data),
// this is what I don't understand: how to populate the variable result with data returned from the model/controller?
           function(result) {
                    $('#myDiv').html(result);
            }
            )
    }

Controller:

function update_multiple()
{

 $this->load->model('products_model');
 $this->products_model->updateMultiple();
// What goes here, to grab data from the model and send it back to the ajax caller?
}

Model:

function updateMultiple()
{
// I have a drop down list to select the field to update. The values of the drop down list look like this: "TableName-FieldName". Hence the explode.

    $table_field = explode("-",$this->input->post('field'));
    $table = $table_field[0];
    $field = $table_field[1];

    $data = $this->input->post('data');

    $rows = explode("
", $data);

    foreach($rows as $key => $row)
    {
        $values = explode(" ", $row);
        $arr[$key]["code"] = $values[0];
        $arr[$key][$field] = $values[1];
    }


   if ($this->db->update_batch($table, $arr, 'code'))
   {
       // Here is the problem. What should I return here, so that it would be sent back to the calling ajax, to populate the result variable?
   }

}
  • 写回答

1条回答 默认 最新

  • donoworuq450547191 2012-11-13 07:41
    关注

    Return json

       if ($this->db->update_batch($table, $arr, 'code'))
      {
       print json_encode(array("status"=>"success","message"=>"Your message here"));
      }
    

    jQuery inside your confirm function

    $.ajax({
    type: "POST",
    url: "<?php echo site_url();?>" + "/products/update_multiple",
    data:  $('form').serialize(),
        dataType: "json",
        success: function(content) {
        if (content.status == "success") {
           $('#myDiv').html(content.message);
        } 
            }
        });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog