javascript - jQuery 获取发回的数据

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

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

问候。

最佳答案

您可以使用一个保留 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]));
    }
}

关于javascript - jQuery 获取发回的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17217727/

相关文章:

javascript - 如何知道何时取消页面重定向或刷新操作,Javascript

jquery - jQuery ajax 延迟数据加载 2 秒

jquery - jqGrid clientArray

jquery - 在页面加载时使用 css3/jquery 滚动圆形图像

database - 客户端应用程序立即响应数据库更新的最佳方式是什么?

javascript - 尝试打印 json 中的关键变量

javascript - 使用 jquery 从 html 输入中获取正确值的问题

javascript - 在 marionette 项目中包含 javascript 文件

javascript - 单元测试通用/同构 Node 包文件

jquery - 如何使用 jQuery 在表格单元格中选择 div