本文介绍了无法正确读取由Cake PHP控制器函数处理Ajax调用发送的json编码成功/失败状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题有点类似于,但我的观察是有点不同。

My problem is somewhat similar to cakephp, jquery, .ajax(), dataType: json, but my observations are little different.

我正在开发一个Cake PHP项目。考虑 opstools 模块的 group_assoc 子模块。因此,有一个函数 group_assoc() opstools_controller.php 中,由ajax调用调用更新组关联。

I am working on a Cake PHP project. Consider a group_assoc submodule of opstools module. So, there is this function group_assoc() inside opstools_controller.php which is invoked by an ajax call to update group associations.

我的ajax帖子是这样 -

My ajax post is like this -

$.post( url,
function(data) 
{
   if(data)
   {

      alert(data.success);  //alerts -> undefined
      alert(data);          //alerts -> {"success":true}  or {"success":false}

      if(data.success)
      {
         //does not work
      }
  }

}, "json");

opstools_controller.php -

function group_assoc()
{
     ...
     ...
     //some code
     ...
     ...
     $success //contains true or false - depending on previous logic

     echo json_encode(array("success" => $success));
}


$ b $ p

So, inside the Ajax response handler function (in the ajax posting part), I am getting a string like {"success":false}.

如何解决这个问题。我记得使用类似的Ajax发布和响应使用json_encode,这在以前的项目与Core PHP(没有蛋糕PHP)完美地工作。这里可能是什么问题?任何指针?

How do I fix this problem. I remember using similar Ajax posting and responding using json_encode, which worked perfectly fine in a previous project with Core PHP (no Cake PHP). What could be the problem here? Any pointers?

更新

我需要明确设置任何标题吗?为什么需要这样做?在哪里检查是否设置了我们正在返回文本。我尝试在回调部分之前放入 header(HTTP / 1.1 200 OK); ,就像在现有代码中一样 - 类似的Ajax处理函数。

Update
Do I need to explicitly set any header? Why would that be needed? Where to check if it is set that we are returning text. I tried putting header("HTTP/1.1 200 OK"); before the echoing part, as is done in the existing code - similar Ajax handler functions.

此外,我在我的模块中设置了 $ this-> autoRender = false;

Also, I have set $this->autoRender = false; in my module.

推荐答案

看起来像我可能会缺少一个参数 $。post / code> API:

It looks to me like you might be missing an argument to the $.post() API:

.post( url, [data,] [success(data, textStatus, jqXHR),] [dataType] )

具体来说,数据参数。 API的示例似乎表明,它足够聪明,可以弄清楚它缺少什么(参数没有出现在API示例中),但它可能值得添加它显式:

Specifically, the data argument. The API's example seems to indicate that it's smart enough to figure out when it's missing (the argument doesn't appear in the API example), but it may be worth adding it explicitly:

$.post( url, null,
  function(data) 
  {
    if(data)
    {

       alert(data.success);  //alerts -> undefined
       alert(data);          //alerts -> {"success":true}  or {"success":false}

    if(data.success)
    {
      //does not work
    }
  }

}, "json");

这篇关于无法正确读取由Cake PHP控制器函数处理Ajax调用发送的json编码成功/失败状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 04:32