var last = 0;
function grabProducts(searchstring) {
var last = 0;
$.post('ajax/products', {
method: 'search',
string: searchstring,
category: $('#search_category').val(),
sort: $('.sort').val()
}, function (data) {
data = $.parseJSON(data);
$.each(data, function (index, b) {
last = "dada";
});
});
}
alert(last);
通过"0"
提醒我。如何将变量设置为"dada"
?
答案 0 :(得分:6)
您无法进行类似的设置,因为$.post()
异步。您必须在传递给$.post()
的回调函数中添加“警报”。
var last=0;
function grabProducts(searchstring) {
var last=0;
$.post('ajax/products', { method: 'search', string: searchstring, category: $('#search_category').val(), sort: $('.sort').val() }, function(data) {
data = $.parseJSON(data);
$.each(data, function(index, b) {
last = "dada";
});
alert(last);
});
}
回调的重点实际上是为您提供一种在HTTP请求完成时运行代码的方法。
答案 1 :(得分:0)
当你POST
某事时,服务器需要时间来回应。这样做:
var last=0;
function grabProducts(searchstring) {
var last=0;
$.post('ajax/products', { method: 'search', string: searchstring, category: $('#search_category').val(), sort: $('.sort').val() }, function(data) {
data = $.parseJSON(data);
$.each(data, function(index, b) {
last = "dada";
});
alert(last);
});
}