【发布时间】:2014-02-18 19:38:20
【问题描述】:
好的,所以我将以下 ajax 发布请求包装在一个模糊事件中,如下所示:
$('#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 发布请求成功后将其传递回回调,因为发布请求已发送。但是我不完全确定如何做到这一点。我已经在我的验证回复中收到一条错误消息,但这是请求的通常自动回复。
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.
}
}
}
我该怎么做?谢谢
【问题讨论】:
-
切换到使用 $.ajax 并将元素作为上下文参数传递。或者,将您的 handleValidation 函数替换为闭包。
-
你的意思是匿名函数吗? .. 如
function(error, my_var)? -
我的第二个示例将显示关闭方式。它是一个使用附加参数执行验证函数的闭包(在这种情况下,闭包是匿名的,但不是必须的)
标签: javascript php jquery ajax cakephp