【发布时间】:2016-09-22 05:19:45
【问题描述】:
我有一个 HTML 表单,我的任务是更新.. 它需要能够应用折扣代码,并且总更新(在提交之前)
我正在使用 AJAX 来:
- 在表单字段中获取用户输入的折扣代码。
- 将这条数据发送到外部的.php脚本
- .php 脚本检查折扣,并返回 true 或 false
- 在这个数据/(php) 响应返回后,我设置了一个 JS var,并调用现有函数来更新“页面”上的一些内容
我目前的问题是我不能设置这个变量。也不能从我的 AJAX 调用中的返回/成功函数调用这个现有函数。
在发布之前进行搜索..(据我了解,这至少部分是我的问题)..我得到 AJAX 是异步的..并且'doMath() 函数可能在 php 响应之前被调用/执行被退回)..
但是我仍然不明白为什么在设置 var 然后检查它时没有更新它?在“成功”回调中??
我读到了关于将 async 设置为 false..
如:
$.ajax({
async: false,
type: "POST",
但也请阅读这是一种不好的方法,应该避免..
当一切都“说完”后,是否有不同或更好的回调可以使用?而不是使用success??
重述:
- 无法设置 AJAX 函数/调用的 var OUTSIDE
- 无法执行/调用现有函数
这是 PHP 以备不时之需(以供全面披露)
$dicountcode = 'code_to_match';
$submittedDiscount = $_POST['var1'];
if($submittedDiscount == $dicountcode){
//echo 'TRUE: '.$submittedDiscount;
echo 'true';
}else{
//echo 'False: '.$submittedDiscount;
echo 'false';
}
实际上,大多数 AJAX 东西都在上面提到的两个项目之外工作。
这是我的代码/方法:
<script type="text/JavaScript" language="JavaScript">
var doDiscount = false;
//math operations
function dothemath() {
//do some math stuff here
//update the page with the new 'amount'
//** uses the above doDiscount var status to knwo wheather to apply a discount or not
}
function applyDiscount(){
//make ajax call and send data to PHP script for discount checking
alert("'else' routine executed...");
$.ajax({
//async: false,
type: "POST",
url: "conservationmanual_discount.php",
//datatype: "html",
datatype: "text",
data:{
//var1: "My Discount Code"
"disCode": $('#discountcode').val()
},
success: function(response) {
alert("PHP RETURN CHECK: "+response);
if(response == "true"){
alert("Discount Code is Valid.");
//update var
doDiscount = true;
//update discount status icon
$("#discountStaus").html(
"<img src='greencheck.png' />"
);
//check doDiscount status after 'update'
console.log("DO DISCOUNT STATUS: "+doDiscount);
//calculate/update total:
dothemath();
}else{
alert("Discount Code is not Valid.");
//update discount status icon
$("#discountStaus").html(
"<img src='redx.png' />"
);
//leave as is/do nothing
console.log("DO DISCOUNT STATUS: "+doDiscount);
}
}
});
}
</script>
更新:
另外.. 我调试得越深,我似乎无法在条件检查中使用响应。
即:
success: function(response) {
alert("PHP RETURN CHECK: "+response);
if(response == "true"){
alert("Discount Code is Valid.");
//update var
doDiscount = true;
//update discount status icon
$("#discountStaus").html(
"<img src='greencheck.png' />"
);
//check doDiscount status after 'update'
console.log("DO DISCOUNT STATUS: "+doDiscount);
//calculate/update total:
dothemath();
如何在条件中使用 PHP 响应/返回数据?
response == "true"
似乎永远不会是真的?尽管我的 ALERTS,显示“响应”是真实的:
alert("PHP RETURN CHECK: "+response);
但是它之后的立即条件检查总是假的??? (可能为什么我无法正确设置 var?
【问题讨论】: