使用 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/