jQuery的$。阿贾克斯:通过额外的参数'成功'回调 [英] jquery $.ajax: pass additional argument to 'success' callback

查看:102
本文介绍了jQuery的$。阿贾克斯:通过额外的参数'成功'回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用$阿贾克斯将数据发布到服务器。不过,我想通过一个额外的参数的'成功'回调告诉回调函数的HTML元素的反应是对的ID。

这是可能的吗?像:

  success_cb(数据,elementid)
{
    (更新与返回服务器数据的elementid)
}

$阿贾克斯({
    ...
    成功:success_cb(elementid)
});
 

解决方案

 函数postForElement(elementId){
  .post的$('/富',someValues​​,功能(数据){
    $(elementId)。html的(返回的服务器:+数据);
  },'JSON');
}
 

通过声明函数文本在同一范围内的 elementId 局部变量,函数变成的关闭的有权访问该局部变量。 (或者有些人可能会说,这只是成为一个的关闭的时候,函数文本还引用了一个未在其范围定义的非全局变量。这只是bandying文字。)

I am using $.ajax to post data to the server. However I want to pass an additional parameter to the 'success' callback to tell the callback function the id of the HTML element the response is for.

It is possible? Like:

success_cb(data, elementid)
{
    (update the elementid with the server returned data)
}

$.ajax({
    ...
    success:success_cb(elementid)
});

解决方案

function postForElement(elementId){
  $.post('/foo',someValues,function(data){
    $(elementId).html("The server returned: "+data);
  },'json');
}

By declaring the function literal in the same scope as the elementId local variable, the function becomes a closure that has access to that local variable. (Or some might say it only becomes a closure when the function literal also references the non-global variable that is not defined in its scope. That's just bandying with words.)

这篇关于jQuery的$。阿贾克斯:通过额外的参数'成功'回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆