You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过AJAX将PHP POST请求返回结果加载到Modal模态框中

问题原因

AJAX请求仅提交了amount参数,未提交currency参数,不满足converter.php的参数校验规则,因此触发错误提示分支。

修复方案

1. 修改index.php中的AJAX代码

补充currency参数的获取和传递,可增加前端校验减少无效请求:

$(document).ready(function(){
  $("#btn").click(function(){
    var vAmount = $("#amount").val();
    // 新增获取币种参数
    var vCurrency = $("#currency").val();
    // 前端简单校验金额合法性
    if(!vAmount || isNaN(vAmount)){
      $("#bingo").html("<p>请输入合法的数字金额</p>");
      return;
    }
    $.post("converter.php",
    {
      amount: vAmount,
      currency: vCurrency
    },
    function(response,status){
      $("#bingo").html(response);
      $("#form")[0].reset();
    });
  });
});

2. 优化converter.php代码(可选)

移除冗余的Your number is输出逻辑,避免和转换结果重复:

<?php
if(isset($_POST['amount']) && is_numeric($_POST['amount']) && isset($_POST['currency'])) {
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, "https://blockchain.info/tobtc?currency=" . $_POST['currency'] . "&value=" . $_POST['amount']);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  $conversion = curl_exec($ch);

  curl_setopt($ch, CURLOPT_URL, "https://blockchain.info/ticker");
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  $prices = json_decode(curl_exec($ch), true);
  curl_close($ch);
?>

<h1>转换结果</h1>
<p><?php echo $_POST['amount']; ?> <?php echo $_POST['currency']; ?> 可兑换 <?php echo $conversion; ?> BTC。</p>

<?php
  if($_POST['currency'] == "USD") { 
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://blockchain.info/charts/market-price?showDataPoints=true&timespan=60days&show_header=true&daysAverageString=7&scale=0&format= JSON");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    $chartdata = json_decode(curl_exec($ch), true);
?>

<?php } ?>
<?php } else { ?>
<p>请填写完整的表单内容。<a href="index.php">返回</a></p>
<?php } ?>

3. 优化弹窗触发逻辑(可选)

当前点击按钮会同时打开弹窗和发起请求,可能出现内容加载闪烁的问题,可调整为请求完成后再打开弹窗:

  • 移除按钮上的data-toggle="modal" data-target="#myModal"属性
  • 修改AJAX回调逻辑手动触发弹窗:
function(response,status){
  $("#bingo").html(response);
  $("#form")[0].reset();
  // 手动打开模态框
  $('#myModal').modal('show');
}

内容的提问来源于stack exchange,提问作者Mark

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 09:54:05