$(document).on("click", "#subtotal", function() {
var total_price=0;
for (i=1; i<= clicks; i++) {
var element = parseFloat($("#total_price_"+i).html());
total_price += parseFloat(element);
var brand_code = $("#brand_"+i).val();
var price = $("#price_"+i).html();
var quantity = $("#quantity_"+i).html();
if (element >=1 ) {
total_price
$("#total").html(total_price);
$.ajax({
type: "POST",
url: "modules/query_jquery/product_select.php",
data: {"new_invoice": "new_invoice", "brand_code": brand_code, "price" : price, "quantity" : quantity , "total_price" : total_price},
dataType: 'json',
success: function (data) {
message = data.message;
window.location.href = data.url;
}
});
}
}
alert(message);
});
我正在尝试提醒消息,但它没有定义? 无法定义在ajax jquery下定义的变量消息? !
答案 0 :(得分:0)
尝试在Ajax完成后执行警报:
success: function (data) {
message = data.message;
window.location.href = data.url;
test();
}
function test() {
if (window.message) {
alert(message);
} else {
alert("global message was not populated");
}
}
答案 1 :(得分:0)
AJAX请求是handeld asynchron!
调用alert时,HTTP请求尚未返回。
使用
提供ajax请求的示例:
$(function () {
var req1 = $.get('test1.json').success(function (data) {
$('body').append(data.hallo);
});
var req2 = $.get('test2.json').success(function (data) {
$('body').append(data.welt);
});
$.when(req1, req2).done(function () {
$('body').append('<br />ajax completed');
}).fail(function () {
$('body').append('<br />ajax failed');
});
});
答案 2 :(得分:0)
如前所述,因为你在ajax成功函数中定义了你的全局变量,这意味着如果这不成功,那么你将无法调用这个变量。
所以在ajax调用之前定义message
是安全的:
message = null;
$(document).on("click", "#subtotal", function() {
var total_price=0;
for (i=1; i<= clicks; i++) {
var element = parseFloat($("#total_price_"+i).html());
total_price += parseFloat(element);
var brand_code = $("#brand_"+i).val();
var price = $("#price_"+i).html();
var quantity = $("#quantity_"+i).html();
if (element >=1 ) {
total_price
$("#total").html(total_price);
$.ajax({
type: "POST",
url: "modules/query_jquery/product_select.php",
data: {"new_invoice": "new_invoice", "brand_code": brand_code, "price" : price, "quantity" : quantity , "total_price" : total_price},
dataType: 'json',
success: function (data) {
message = data.message;
window.location.href = data.url;
}
});
}
}
alert(message);
});