【问题标题】:json object posted to codeigniterjson 对象发布到 codeigniter
【发布时间】:2012-05-28 11:37:55
【问题描述】:

我犯了一个非常简单的错误,但无法找到它。 我使用 AJAX 将 JSON 对象发布到 CodeIgniter 控制器,但无法在控制器函数中检索此值。 我的代码是

AJAX 代码:

 $.ajax({
    type: "POST",
    contentType: "application/json",
    data: "{eventdata:" + JSON.stringify(eventToSave) + "}",
    url: "<?php echo $base?>/index.php/welcome/addEvent",
    dataType: "json",
    success: function (data) {      
        alert(data);        
        $('#calendar').fullCalendar('renderEvent', event, true);
        $('.qtip').remove();
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        debugger;
    }
});

在控制台中,JSON 对象以如下格式显示:

{
    eventdata: {
        "EventID": 170,
        "StartDate": "Thu May 10 2012 00:00:00 GMT+0530 (India Standard Time)",
        "EndDate": "Thu May 10 2012 00:00:00 GMT+0530 (India Standard Time)",
        "EventName": "sdsfddsf"
    }
} 

CodeIgniter addEvent 函数:

$json_output[]=(array)json_decode($this->input->post());        
print_r($json_output);

我也尝试了各种其他选项,但无法从我需要存储在数据库中的 json 对象中获取值。请告诉我一些从 json 对象中检索该值然后将其存储在数据库中的方法

【问题讨论】:

    标签: ajax codeigniter json


    【解决方案1】:

    如果可行,试试这个。

    $json = file_get_contents('php://input');
    $json = stripslashes($json);
    $json = json_decode($json);
    
    convert the object array to array
    $array =  (array) $json;
    

    【讨论】:

    • 嗨,Marvz73,您能具体说明 stripslashes($json) 与发帖人提出的问题的关系吗?
    • 这是一种非常迂回的获取POST数据的方式。
    【解决方案2】:

    这看起来不对。

     url: "<?php echo $base?>/index.php/welcome/addEvent",
    

    您确定您实际使用了正确的控制器方法吗?你检查源代码了吗?

    尝试这样做(使用 URL 助手):

    url: "<?php echo site_url('welcome/addEvent'); ?>",
    

    【讨论】:

    • 嘿,它是正确的 url。事实上,我能够在 codeigniter 控制器中调用正确的方法。我定义了相对于我的项目的 $base。这根本不会引起问题
    • 请告诉我如何在 php 中检索这个 json 对象。
    猜你喜欢
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 2012-03-20
    • 2017-10-09
    • 1970-01-01
    • 1970-01-01
    • 2012-01-25
    • 2013-05-31
    相关资源
    最近更新 更多