Javascript php无法将json数据解析为ajax

Javascript php无法将json数据解析为ajax,javascript,php,json,ajax,cakephp,Javascript,Php,Json,Ajax,Cakephp,这个问题在stackoverflow中很常见。我在这个论坛上看到了太多像我这样的问题的解决方案。但这没有帮助。所以我把它贴出来了。请友好地回答我 问题: 我试图从cakephp控制器函数发送一个整数来查看ajax调用。 我在这里和其他论坛上尝试的所有解决方案都不断出现这个错误 “SyntaxError:JSON中位于位置0的意外标记a” 请告诉我查看我的代码有什么问题: 我可以清楚地看到,我在php中以json格式获取数据,同时进行echo,但在主Ajax调用中没有 Console says :

这个问题在stackoverflow中很常见。我在这个论坛上看到了太多像我这样的问题的解决方案。但这没有帮助。所以我把它贴出来了。请友好地回答我

问题: 我试图从cakephp控制器函数发送一个整数来查看ajax调用。 我在这里和其他论坛上尝试的所有解决方案都不断出现这个错误

“SyntaxError:JSON中位于位置0的意外标记a”

请告诉我查看我的代码有什么问题: 我可以清楚地看到,我在php中以json格式获取数据,同时进行echo,但在主Ajax调用中没有

Console says :the result is {"data":1}
控制器:

public function addit()
    {
        $mycount      = 1;
        $responseJSON = array(
            'data' => $mycount
        );
        //$responseJSON = array('status' =>'true', 'result'=>$arr);
        header('content-type:application/json');
        $response = json_encode($responseJSON);
        echo $response;
    }
ajaxcall在视图中:

$(document).ready(function(){
        $('#bn_cart').click(function(event){
          //alert('clicked');
          var form_data = $(this).serialize();

          var id = $('#id').val();
          alert("your item id is "+ id);
          var csrfToken = <?php echo(json_encode($this->request->getParam('_csrfToken'))) ?>;
               //alert("your form data "+csrfToken);
              event.preventDefault();
              $.ajax({
                headers: {
                      'X-CSRF-Token': csrfToken
                    },
                  url:'../addit',
                  type:'POST',

                  data: { id : id },
                  dataType:'json',

              success:function(xhr, response){
                    var respons = response;
                    console.log("conosle success says "+ (respons.result));
                    alert("success"+respons.result);

                },
              error:function(xhr, e,etype,response){
                    //alert("<br>error<br>"+ error.responseText.message);
                    alert("response = "+ response +"xhr = "+ xhr + "  e = " + e + "  etype = "+ etype);
                    console.log(" response =" + response + "error ="+ e +"xhr = "+ xhr + "  etype = "+ etype );
                    //  $("#result").html(error.Message);
                    // alert('error ='+(error.Message));
                  }
          });

        });
    });


Network>Header:
Request URL: http://localhost/shoppingCart/products/addit
Request Method: POST
Status Code: 200 OK
Remote Address: [::1]:80
Referrer Policy: no-referrer-when-downgrade
Cache-Control: no-store, no-cache, must-revalidate
Connection: Keep-Alive
Content-Length: 583
Content-Type: text/html; charset=UTF-8
Date: Tue, 23 Oct 2018 14:10:08 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive: timeout=5, max=99
Pragma: no-cache
Server: Apache/2.4.29 (Win32) OpenSSL/1.0.2n PHP/7.1.15
X-DEBUGKIT-ID: 182187f0-546d-48d4-9e5a-6746a40dba64
X-Powered-By: PHP/7.1.15
Accept: application/json, text/javascript, */*; q=0.01
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 4
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Cookie: csrfToken=0a8a1f6e98fe8274e80f9bdcb3ba5df66a5af4296126302d3e79bf44e856ed720438947bb93f041f772ac1e39d083aa2d88c5159697c9843a8b04eace893260b; CAKEPHP=mhphclr8cuvacrlotbit45dd3l; csrftoken=t0p47S5P7NBcwGGQ9sfuNGLi5JJDkll8ifuCWhG3W6MRSIewe9GtRNjanPUqms54
Host: localhost
Origin: http://localhost
Referer: http://localhost/shoppingCart/products/view/2
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36
X-CSRF-Token: 0a8a1f6e98fe8274e80f9bdcb3ba5df66a5af4296126302d3e79bf44e856ed720438947bb93f041f772ac1e39d083aa2d88c5159697c9843a8b04eace893260b
X-Requested-With: XMLHttpRequest


Network>>Response : 
{"data":1}
$(文档).ready(函数(){
$('bn_cart')。单击(函数(事件){
//警报(“点击”);
var form_data=$(this).serialize();
var id=$('#id').val();
警报(“您的项目id为”+id);
var csrfToken=;
//警报(“您的表单数据”+csrfToken);
event.preventDefault();
$.ajax({
标题:{
“X-CSRF-Token”:csrfToken
},
url:“../addit”,
类型:'POST',
数据:{id:id},
数据类型:'json',
成功:功能(xhr,响应){
var响应=响应;
log(“conosle success说”+(response.result));
警报(“成功”+响应结果);
},
错误:函数(xhr、e、etype、response){
//警报(“
错误
”+错误.responseText.message); 警报(“response=“+response+”xhr=“+xhr+”e=“+e+”etype=“+etype”); console.log(“response=“+response+”error=“+e+”xhr=“+xhr+”etype=“+etype”); //$(“#结果”).html(error.Message); //警报('error='+(error.Message)); } }); }); }); 网络>标题: 请求URL:http://localhost/shoppingCart/products/addit 申请方式:邮寄 状态代码:200 OK 远程地址:[::1]:80 推荐人策略:降级时无推荐人 缓存控制:没有存储,没有缓存,必须重新验证 连接:保持活力 内容长度:583 内容类型:text/html;字符集=UTF-8 日期:2018年10月23日星期二14:10:08 GMT 到期时间:1981年11月19日星期四格林威治标准时间08:52:00 保持活动状态:超时=5,最大=99 Pragma:没有缓存 服务器:Apache/2.4.29(Win32)OpenSSL/1.0.2n PHP/7.1.15 X-DEBUGKIT-ID:182187f0-546d-48d4-9e5a-6746a40dba64 X-Powered-By:PHP/7.1.15 接受:application/json,text/javascript,*/*;q=0.01 接受编码:gzip,deflate,br 接受语言:en-US,en;q=0.9 连接:保持活力 内容长度:4 内容类型:application/x-www-form-urlencoded;字符集=UTF-8 Cookie:csrfToken=0a8a1f6e98fe8274e80f9bdcb3ba5df66a5af4296126302d3e79bf44e856ed720438947bb93f041f772ac1e39d083aa2d88c5159697c9843a8b04eace893260b;CAKEPHP=mhphclr8cuvacrlotbit45dd3l;csrftoken=t0p47S5P7NBcwGGQ9sfuNGLi5JJDkll8ifuCWhG3W6MRSIewe9GtRNjanPUqms54 主机:本地主机 来源:http://localhost 推荐人:http://localhost/shoppingCart/products/view/2 用户代理:Mozilla/5.0(Windows NT 6.1;Win64;x64)AppleWebKit/537.36(KHTML,类似Gecko)Chrome/69.0.3497.100 Safari/537.36 X-CSRF-Token:0a8a1f6e98fe8274e80f9bdcb3ba5df66a5af4296126302d3e79bf44e856ed720438947bb93f041f772ac1e39d083aa2d88c5159697c9843a8b04eace893260b X-request-With:XMLHttpRequest 网络>>响应: {“数据”:1}
您需要返回json编码的响应。您正在尝试回显一个非json编码的响应,但该响应将不起作用

public function addit()
{
    $mycount      = 1;
    $responseJSON = array(
        'data' => $mycount
    );
    //$responseJSON = array('status' =>'true', 'result'=>$arr);
    header('content-type:application/json');
    return json_encode($responseJSON);
}
Ajax调用:

success:function(data, status, jqxhr)
            var respons = data;
            console.log("conosle success says "+ (respons.result));
            alert("success"+respons.result);

        },

echo“
结果是”$反应
将使响应成为无效的JSON,因为它不是有效的JSON。只需回显
$response
。从您的echo@JonStirling谢谢你的回复。不幸的是,它还没有帮助..同样的错误:response=undefined xhr=[object]e=parsererror etype=SyntaxError:JSON中位置处的意外标记a0@MasivuyeCokile谢谢你的回复…但这对我没什么帮助yet@vins尝试在ajax设置中添加
encode:true
,并硬刷新页面您需要向OP解释您在ddnt中做了什么do@Bernard帕戈加感谢您的回复。我已经尝试过很多次了,它给出了不同的错误:response=undefinedxhr=[object object]e=error etype=Internal Server error(我还可以在控制台中看到数据),而且成功回调将数据作为第一个参数,而不是xhr对象:。