1

使用 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 成功时获取发送的数据以进行处理,或者至少在成功时将该参数传递给自定义回调。

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

问候。

4

1 回答 1

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]));
    }
}
于 2013-06-20T15:55:48.137 回答