为什么我的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);
}
}
});
}
答案 0 :(得分:1)
您过早关闭了if-
声明的大括号:
if (y > x) {
$.getJSON($SCRIPT_ROOT + '/filterSize/' + varValue)
//} <-- TOO EARLY
.success(function (data) {
....
});
} <-- SHOULD BE HERE INSTEAD
在if
回调后结束.success()
语句。
答案 1 :(得分:1)
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。