gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:36:52 24 4
gpt4 key购买 nike

好的,所以我将以下 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com