Ajax请求总是会出错

时间:2015-10-13 03:16:49

标签: javascript php jquery json codeigniter

实际上我在我的项目中使用CodeIgniter作为后端,在我的前端使用jQuery 2.1.3。

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

当我运行此功能时:

var side = 'biltyveri';
var request_checkUrl = '/antibot/antibot_data?script=' + side;

$.ajax({
    url: request_checkUrl,
    type: "GET",
    dataType: 'json',
    beforeSend: function () {
        document.title = "Running...";
    },
    success: function (data) {
        document.title = "Success.";
        alert("success");
    },
    error: function (data) {
        alert("ERROR");
        console.log(data);
    }
});

始终显示ERROR并且从不显示成功功能。我不知道我做错了什么。

在我的控制器中,我正在运行此代码:

echo $this->framework->ajaxJSONResponse(200, $data);

这是它给出响应的函数json:

function ajaxJSONResponse($status, $data) {
    header('Content-type: application/json');
    $response             = array();
    $response['status']   = $status;
    $response['data']     = $data;
    return json_encode($response);
}

上面的代码给出了如下的json响应:

{
    "status": 200,
    "data": {
        "text": "en TV",
        "images": [
            {
                "hash": "47a32df0c4b1f0b522e5faf35a46aacd95fe0ed4",
                "file": "ABImage_plane_1"
            },
            {
                "hash": "e11f83f4411364546329c8a8bf88da0dffd27029",
                "file": "ABImage_house_2"
            },
            {
                "hash": "93b4454ac09e7d7478fa2d25322e0e784370ea7a",
                "file": "ABImage_car_5"
            },
            {
                "hash": "36fac21a830b922edb507487d833556aeb9688f7",
                "file": "ABImage_clock_4"
            },
            {
                "hash": "cd1df47e052a5d0d50dab61b3e716339be0c6e68",
                "file": "ABImage_TV_3"
            },
            {
                "hash": "59e7f70b7874a500e576e25077adf254c52f5ee8",
                "file": "ABImage_train_4"
            }
        ]
    }
}

非常感谢你。

编辑: 路线:

$route['antibot/antibot_data'] = "antibot/antibot_interface_controller/antibot_data";

背景:ajax throwing error with right outcome

1 个答案:

答案 0 :(得分:1)

如果您使用Codeigniter,则网址错误

var side = 'biltyveri';
var request_checkUrl = '/antibot/antibot_data?script=' + side;

这应该是

url: "<?php echo base_url()?>Controller_name/method_name",

和方法应为post

type: "POST",

并使用

传递数据
data : {"script : side, someOther: anotherValue"}

在控制器方法中,使用此

$script = $_POST['script'];
$someOther = $_POST['anotherValue'];