[英]JQuery Ajax call not working in If statement
為什么我的Ajax調用無法在if語句中起作用? 我在這里可能做的是根本上錯誤的事情,因為我對JS或Ajax經驗不足。 謝謝
起作用的js函數是:
function filter(varType, varValue) {
var $products = $('#products');
$.getJSON($SCRIPT_ROOT + '/filterSize/' + varValue)
.success(function (data) {
$products.empty(); // clear html from container
var elt0 = '<div class="page-content"><h1 id="shoes">Shoes</h1></div>';
$products.append(elt0);
if (Object.keys(data.shoes).length === 0) {
none = '<span class="noresults">No results</span>';
$products.append(none);
}
else {
var numItems = (Object.keys(data.shoes).length);
for (index = 0; index < numItems ; ++index) {
var elt1 = Flask.url_for("static", {"filename": data.shoes[index].img1});
var elt2 = '<div id="item" class="col-md-4"><div class="products"><a href="shop/item/' + data.shoes[index].id + '"><h5>' + data.shoes[index].name + '</h5><img src="' + elt1 + '" alt="" width="200px" height="125px"></a></div>';
$products.append(elt2);
}
}
});
}
但是,如果我要這樣做,它突然停止工作:
function filter(varType, varValue) {
var $products = $('#products');
var x = 5
var y = 6
if (y > x) {
$.getJSON($SCRIPT_ROOT + '/filterSize/' + varValue)
}
.success(function (data) {
$products.empty(); // clear html from container
var elt0 = '<div class="page-content"><h1 id="shoes">Shoes</h1></div>';
$products.append(elt0);
if (Object.keys(data.shoes).length === 0) {
none = '<span class="noresults">No results</span>';
$products.append(none);
}
else {
var numItems = (Object.keys(data.shoes).length);
for (index = 0; index < numItems ; ++index) {
var elt1 = Flask.url_for("static", {"filename": data.shoes[index].img1});
var elt2 = '<div id="item" class="col-md-4"><div class="products"><a href="shop/item/' + data.shoes[index].id + '"><h5>' + data.shoes[index].name + '</h5><img src="' + elt1 + '" alt="" width="200px" height="125px"></a></div>';
$products.append(elt2);
}
}
});
}
您過早關閉了if-
語句的花括號:
if (y > x) {
$.getJSON($SCRIPT_ROOT + '/filterSize/' + varValue)
//} <-- TOO EARLY
.success(function (data) {
....
});
} <-- SHOULD BE HERE INSTEAD
在.success()
回調之后結束if
語句。
if (y > x) {
$.getJSON($SCRIPT_ROOT + '/filterSize/' + varValue)
.success(function (data) {
$products.empty(); // clear html from container
var elt0 = '<div class="page-content"><h1 id="shoes">Shoes</h1></div>';
$products.append(elt0);
if (Object.keys(data.shoes).length === 0) {
none = '<span class="noresults">No results</span>';
$products.append(none);
}
else {
var numItems = (Object.keys(data.shoes).length);
for (index = 0; index < numItems ; ++index) {
var elt1 = Flask.url_for("static", {"filename": data.shoes[index].img1});
var elt2 = '<div id="item" class="col-md-4"><div class="products"><a href="shop/item/' + data.shoes[index].id + '"><h5>' + data.shoes[index].name + '</h5><img src="' + elt1 + '" alt="" width="200px" height="125px"></a></div>';
$products.append(elt2);
}
}
});
}
這是有效的語法。 您需要在圓括號內移動.success。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.