好的,我在下面有以下HTML,AJAX和PHP脚本。我希望在处理AJAX请求时获取$deduct
值以更新<span id="mywallet"></div>
字段。我怎么能这样做?
示例表格
<form>
<span id="mywallet">$<?php echo $wallet; ?></span>
</form>
flip-process.php结构示例
<?php
if($_POST){
//process everything
$deduct = (something calculated);
if(success){
$msg = "success";
}else{
$msg = "fail";
}
}
echo $msg;
?>
Ajax脚本
$(document).ready(function() {
$("#submit").click(function() {
var dataString = {
flip: $("#flip").val(),
amount: $("#amount").val(),
};
$.ajax({
type: "POST",
url: "flip-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#process-flipping").hide();
$(".coin-flip").show();
},
success: function(html){
setTimeout(function(){
$(".message").html(html).fadeIn();
$("#process-flipping").show();
$(".coin-flip").hide();
},3000);
}
});
return false;
});
});
答案 0 :(得分:1)
最好的方法是使用json
PHP
<?php
$response = [];
if($_POST){
//process everything
$deduct = (something calculated);
if(success){
$response["deduct"] = $deduct;
}else{
$response["msg"] = "your message here";
}
}
header("Content-type:application/json; charset: UTF-8");
echo json_encode($response);
?>
JS
$(document).ready(function() {
$("#submit").click(function() {
var dataString = {
flip: $("#flip").val(),
amount: $("#amount").val(),
};
$.ajax({
type: "POST",
dataType : "json",
url: "flip-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#process-flipping").hide();
$(".coin-flip").show();
},
success: function(json){
//json.deduct will has the value you want
}
});
return false;
});
});
答案 1 :(得分:1)
是的,json是最好的解决方案:
<?php
if($_POST){
//process everything
$deduct = (something calculated);
if(success){
$msg = "success";
}else{
$msg = "fail";
}
echo json_encode(array('status' => $msg, 'deduct' => $deduct));
}
?>
和ajax success
:
success: function(json){
setTimeout(function(){
$(".message").html(json.status).fadeIn();
$("#process-flipping").show();
$(".coin-flip").hide();
},3000);
if(json.status == 'success')
$('#mywallet').html('$' + json.deduct);
}