jQuery收回数据

时间:2013-06-20 15:28:08

标签: javascript jquery ajax

使用jQuery.get方法时如何获取数据?

function send_data(pgId)
{
    for(var i = 0; i < pgId.length; i++)
    {
        // $.get(url, data, success(data, textStatus, jqXHR))
        $.get('index.php?page=' + pgId[i], pgId[i], function(respTxt, status, xhr)
        {
            if(status === "success")
            {
                alert("Data received: " + respTxt + "\n");
                alert("Data sent: " + pgId[i]); //<-- ???
            }
        });
    }
}

我发送的参数是可选的,服务器不接受该参数,我唯一想要的是在成功使用时将该参数传递给回调函数。 pg_array是DIV ID的数组。

我需要在ajax成功时将数据发送到进程,或者在成功时至少将该参数传递给自定义回调。

我也是网络开发的新手,所以道歉。我经常搜索,但我无法理解它显示的任何样本。

问候。

1 个答案:

答案 0 :(得分:0)

你可以使用一个闭包来保持ID的值:

function send_data(pgId) {

    var callbackWithId = function (pgId) {
        //This will keep the pgId for the returned function
        return function(respTxt, status, xhr) {
            if(status === "success") {
                alert("Data received: " + respTxt + "\n");
                alert("Data sent: " + pgId);
            }
        }
    }

    for(var i = 0; i < pgId.length; i++) {
        $.get('index.php?page=' + pgId[i], pgId[i], callbackWithId(pgId[i]));
    }
}
相关问题