Codeigniter Ajax JSON返回不起作用

时间:2016-04-09 08:16:16

标签: php jquery json ajax codeigniter

我有一个视图,里面有一个按钮,点击后我想从控制器中检索一些数据。

这是在视图中:

    <script>
    $('.ajaxBtn').click(function(e) {
        e.preventDefault();
        $.ajax({
            type: "POST",
            url: '/ajaxController',
            data: "",
            dataType:'json',
            success : function(response){ console.log(response); alert(response)}
        });
    });
</script>

我的控制器看起来像这样:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class ajaxController extends MY_Controller
{
    function __construct()
    {
        parent::__construct();
    }

    function index()
    {
        echo json_encode("datafromajax");
    }


}

我的路线定义如下:

$route['ajaxControl'] = "ajaxController/index";

但即使响应为200,我也没有响应数据。

感谢您的帮助

EDIT2 //从在线资源中加载JSON正常

编辑//回复:

  

XHR已加载(索引 - 200 OK - 39.48300000047311ms - 35.38KB)VM3852:3   http://davids-macbook-pro.local:5757/ajaxController/index VM3853:3   对象{startedDateTime:“2016-04-09T08:45:16.133Z”,时间:   39.48300000047311,request:Object,response:Object,cache:Object ...} cache:Object__proto __:Object__defineGetter__:    defineGetter () defineSetter defineSetter () lookupGetter lookupGetter () lookupSetter lookupSetter ()构造函数:Object()hasOwnProperty:hasOwnProperty()isPrototypeOf:   isPrototypeOf()propertyIsEnumerable:   propertyIsEnumerable()toLocaleString:toLocaleString()toString:   toString()valueOf:valueOf()获取 proto :获取 proto ()设置    proto :设置 proto ()连接:“122019”pageref:“page_7”请求:ObjectbodySize:0cookies:Array [2] headers:   Array [11] headersSize:1099httpVersion:“HTTP / 1.1”方法:   “POST”queryString:Array [0] url:   “http://davids-macbook-pro.local:5757/ajaxController/index” 的:   Objectresponse:Object_transferSize:35380bodySize:34973content:   Objectcookies:Array [0] headers:Array [10] headersSize:407httpVersion:   “HTTP / 1.1”redirectURL:“”状态:200statusText:“确定”原型:   ObjectstartedDateTime:“2016-04-09T08:45:16.133Z”时间:   39.48300000047311timings:Object__proto__:Object

1 个答案:

答案 0 :(得分:0)

在json_encode()

中将字符串chnage为数组

echo json_encode("datafromajax");echo json_encode(['data'=>"datafromajax"]);