【问题标题】:Pass a value from controller JSON to view Ajax in CodeIgniter从控制器 JSON 传递一个值以在 CodeIgniter 中查看 Ajax
【发布时间】:2012-12-26 12:18:18
【问题描述】:

问题是我得到了 false 的对话框,但查询运行正常并且值已成功添加到数据库中。它应该打印正确,但它给了我一个错误。我通过Firebug 也检查了值 res = 1,但我不知道其中有什么问题。

我的观点:

$.ajax({
    url: "<?php echo site_url('itemsController/additems'); ?>",
    type: 'POST',
    data: form_data,
    success: function(msg) {
        if(msg.res == 1)
        {
            alert(true);
        }
        else
        {
            alert(false);
        }
    }
});

控制器:

        $result = array();
        $this->load->model('itemsModel');
        $query = $this->itemsModel->addItemstoDB($data);

        if ($query){  //&& any other condition
            $result['res'] = 1;
        }
        else
        {
            $result['res'] = 0;
        }
        echo json_encode($result); //At the end of the function.
    }
}

【问题讨论】:

    标签: php jquery ajax json codeigniter


    【解决方案1】:

    通知退货。

        if ($query){
            $result['res'] = 1;
        }
        else 
        {
            $result['res'] = 0;
        }
        return json_encode($result);//at the end of the function.
    }
    

    【讨论】:

    • 你想回应,而不是返回。
    • 您必须回显才能不返回。这里是 ajax。
    【解决方案2】:

    尝试将您的dataType 设置为json,以便从服务器发回的数据被解析为JSON

    $.ajax({
        url: "<?php echo site_url('itemsController/additems'); ?>",
        type: 'POST',
        data: form_data,
        dataType: 'json',
        success: function(msg) {
            if(msg.res == 1) {
                alert(true);
            }
            else
            {
                alert(false);
            }
        }
    });
    

    【讨论】:

    • 是的,谢谢ssssssssssssssssssss ...我缺少定义json数据类型。
    猜你喜欢
    • 1970-01-01
    • 2017-09-16
    • 2012-09-02
    • 2016-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-22
    • 2017-03-15
    相关资源
    最近更新 更多