【问题标题】:Ajax Response from CakePHP Controller returning nullCakePHP 控制器的 Ajax 响应返回 null
【发布时间】:2010-07-06 14:49:17
【问题描述】:

我正在尝试通过对 cakephp 控制器的 ajax 调用来验证输入字段 我的 Ajax 是:

$("#UserAlphaCode").change(function () {
        $.ajax({
            type: "post",
            url: '<?php echo $this->webroot ?>' + "/alpha_users/checkCode",
            data: ({code : $(this).val()}),
            dataType: "json",
            success: function(data){
                alert (data);
            },
            error: function(data){
                alert("epic fail");
            }
        });
    });

我的控制器代码

function checkCode() {
        Configure::write('debug', 0);
        $this->autoRender = false;
        $codePassed = $this->params['form']['code'];
        $isCodeValid = $this->find('count',array('conditions'=> array('AlphaUser.code' => $codePassed)));
        if ($isCodeValid == 0){
            $codeResponse = false;
        } else {
            $codeResponse = true;
        }
        echo json_encode ($codeResponse);   
    }

我很确定我在这里使用了错误的 $this->params 来访问从 ajax 请求发送的数据。我应该怎么做?

【问题讨论】:

    标签: ajax cakephp controllers


    【解决方案1】:

    尝试类似:

    $codePassed = $_POST['code']

    你也可以试试:

    $this->log($codePassed,LOG_DEBUG);
    

    在那里的某个地方检查tmp/logs/debug.log中的输出

    使用 firebug 将有助于调试传输。

    【讨论】:

    • 在尝试了您的建议g $codePassed = $_POST['code'] 我能够将其返回到警报(数据)我通过更改我的控制器输出从 echo json_encode ($codeResponse) ;回显 json_encode ($codePassed);这行得通。但是当我尝试返回 $isCodeValid 时,我得到一个空响应。
    • 也许我的 $isCodeValid = $this->find('count',array('conditions'=> array('AlphaUser.code' => $codePassed))) 有问题
    • 我检查了标头内容,但什么也没得到,但 chrome 调试器中有一个错误提示“未捕获的 TypeError:无法读取属性 'codeResponse' of null”
    • 你在控制器里,对吧?该行应为: $isCodeValid = $this->AlphaUser->find(...
    【解决方案2】:

    不知道为什么会返回 null,但我通常使用$this-&gt;data 来获取表单数据。

    你试过debug($this-&gt;params)吗?如果您没有用于测试请求的非 AJAX 表单,请使用 Firebug 或 Wireshark 查看服务器为 debug() 调用返回的内容——因为它会因不在 JSON 中而破坏 jQuery 的 AJAX 处理程序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-30
      • 1970-01-01
      • 2016-09-10
      相关资源
      最近更新 更多