javascript - cakePHP- Ajax post请求-成功后将数据发送回回调

标签 javascript php jquery ajax cakephp

好的,所以我将以下 ajax post 请求包装在一个模糊事件中,如下所示:

$('#name, #surname, #email').blur(function(e){        
        $.post(
            '/validate_form', // it will submit to the validate_form action
            {field: $(this).attr('id'), value: $(this).val()}, 
            handleValidation
        );

    });

在我的 handleValidation 回调中,我想取回触发模糊事件的元素的 ID(即 field)。所以我想到的方法是在 ajax post 请求成功后将其传递回回调,因为 post 请求已发送。但是我不完全确定如何执行此操作。我已经在我的验证响应中收到一条错误消息,但这是请求的通常自动响应。

function handleValidation(error, {//i want to get another variable sent here..}) {
        if (error.length > 0) {
            if ($('{placeholder for field id}-notEmpty').length == 0) {
                $('#{placeholder for field id').after('<div id="{placeholder for field id-notEmpty" class="error-message">' + error + '</div>');
            }
        }else{
            $('#{placeholder for field id-notEmpty').remove();
        }
    } 

public function validate_form(){            
        if($this->RequestHandler->isAjax()){
        $this->request->data['Model'][$this->request->data['field']] = $this->request->data['value'];
        $this->Donor->set($this->request->data);
             if($this->Model->validates()){
               $this->autoRender = FALSE;
             }else{
                //somewhere here, i need to pass in $this->request->data['field'] back to callback function handleValidation.
             }

        }
}

我该怎么做?谢谢

最佳答案

有几种方法可以做到这一点,所有方法都围绕着访问this。您可以将它作为参数传递给您的回调,将它作为上下文传递给您的回调,或者让您的回调成为闭包。

$.ajax('/validate_form',{
    data: {
        field: $(this).attr('id'),
        value: $(this).val()
    }
    context: this,
    success: handleValidation
});

function handleValidation() {
    console.log(this); // the element that you acted on
}

var self = this;
$.post(
    '/validate_form', // it will submit to the validate_form action
    {field: $(this).attr('id'), value: $(this).val()}, 
    function (data) {
        handleValidation(data,self);
    }
);
function handleValidation(data,el) {
    console.log(el); // the element that you acted on
}

关于javascript - cakePHP- Ajax post请求-成功后将数据发送回回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21863687/

相关文章:

javascript - 如何使用单选按钮启用特定文本字段?

javascript - 如何修复: "TypeError: Cannot read property ' tag' of undefined"error in discord. js

PHP 忽略错误并继续处理

java - Html5 Web 存储不在第二页中显示数据

javascript - 使用 css 和 jQuery 制作图像旋转

javascript - 输入类型文件,仅通过单击按钮触发弹出窗口

javascript - 无法在 react native map 内移动按钮

javascript - 将 JavaScript 中的内容打印到 HTML/PHP 页面的表格中

php - 无法更新 php 中的复选框

javascript - 单击外部选择器触发事件