Adding a parameter to Jquery ajax call
I have this JSON Ajax function
$.ajax({
url: "?page=" + page,
dataType: "json",
success: function(data) {
$.each(data, function() {
$("#feed").append("<li>" + this.message + "</li>");
});
}
});
However, I would like to be able to pass a variable into it, so this.message could also be this.image, or this.link. I tried doing this.
$.each(data, function() {
$("#feed").append("<li>" + myVar + "</li>");
});
and setting myVar = 'this.picture'
, however it treated myVar as a string and it didn't work. How can I pass in a variable so I can achieve my goal?
Thanks in advance!
Try:
... + this[myVar] + ...
where myVar = 'picture'
, or whatever other field it is that you want to display.
This is the standard syntax for accessing a named property of an object when the name is itself a variable rather than a literal token.
First of all you must make sure that "picture" or "link" are being passed into your returned Json object.
Then try replacing this with data as in: data.picture or data.link.
You want that the callback to be parameterized use the $.when
Use $.when
var m = $.ajax({
url: "?page=" + page,
dataType: "json"
});
var callback = function(link)
{
return function(data){
alert(link); //Can access data and link here
}
}
$.when(m)
.then(callback(link));
精彩评论