如何在不使用 ajax 刷新的情况下在我的页面上显示我的 php 响应?

Posted

技术标签:

【中文标题】如何在不使用 ajax 刷新的情况下在我的页面上显示我的 php 响应?【英文标题】:How do i get to show my php response on my page without refreshing with ajax? 【发布时间】:2017-02-18 03:27:52 【问题描述】:

我有这个表格

    <form action="send.php" method="post">
          <div class="col-md-12">
            <div class="input-group input-group-lg">
              <span class="input-group-addon" id="sizing-addon1"><i class="fa fa-credit-card"></i></span>

             <input id="nfc" name="nfc" type="text" required class="form-control" placeholder="Wristband UID will appear here...." aria-describedby="sizing-addon1">
             </div>

<br>
              <div class="input-group input-group-lg">
                  <span class="input-group-addon" id="sizing-addon1"><i class="fa fa-phone"></i></span>
                   <input id="phone" name="phone" type="text" value="254" required class="form-control" placeholder="Registered Phone Number" aria-describedby="sizing-addon1">
             </div>  

<br>
          <button type="submit" class="btn btn-color btn-lg">OK, Im Done</button>
</div>
            <div id="alert"></div>
</form>

我想通过这个 php 脚本处理输入:

<?php 
$nfc = $_POST["nfc"];
$phone = $_POST["phone"];


$post = [
'nfc' => $nfc,
//'password' => '9907',
'phone' => $phone,

];

header( "Content-Type: application/json" );

$ch = curl_init('myAPIUrl');//posts input to my api and i get a response

curl_setopt($ch, CURLOPT_POSTFIELDS, $post);


curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);

curl_close ($ch);

header( "refresh:1400;url=http://www.swype.co.ke/counter/index.html" );

var_dump($server_output);
?>

并在同一页面的 div id "ALERT" 中显示表单响应。我的 API URL 是一个 api,其参数是输入字段。我得到如下所示的 api 响应。

string(121) ""idUser":42,"rfid":"4534543","username":"","transactionStatus":"NFC tag has been updated successfully","statusCode":200"

【问题讨论】:

你不能没有 ajax .. 或者没有刷新页面 .. 如果您只使用php,则必须以某种方式刷新页面以反映结果。 @scaisEdge ajax 不是唯一的方法......只是最常见的一种。其他几种方法也可以做到这一点 @charlietfl 正确.. 但必须做一些事情.. ajax.. 提交.. @charlietfl 我如何用 ajax 做到这一点? 【参考方案1】:

为了通过 PHP 处理输入,您需要将表单数据发送到服务器。为了显示来自服务器响应的警报,您需要提交表单(从而刷新页面)或使用 AJAX 提交表单数据并等待响应。


现在您正在使用 PHP 来做一些您可以通过 AJAX 来做的事情。试试这样的:

$( "form" ).submit(function( event ) 
  // request json with 
  $.getJSON( "http://www.swype.co.ke/counter/index.html", 
    // whatever data you want to send from your form
     name: "John", time: "2pm" ,
    function( data ) 
      // show the result of processing the data
      alert(data);
    
  );

  // prevent form from refreshing the page
  event.preventDefault();
);

【讨论】:

如何使用 ajax 提交表单数据并等待我的回复? 有点像丽贝卡?

以上是关于如何在不使用 ajax 刷新的情况下在我的页面上显示我的 php 响应?的主要内容,如果未能解决你的问题,请参考以下文章

如何在不刷新页面的情况下在屏幕上显示新记录?

如何在不刷新页面的情况下在 ReactJS 中重新加载?

Vuex:在不编写 itvuex 的情况下在页面刷新时保持状态?

如何在不影响网站页面速度的情况下在我的网站上使用谷歌字体

使用 jQuery-AJAX 向 PHP 提交表单并在不刷新的情况下在 div 中显示新内容的问题

如何使用 Django、Ajax、jQuery 在不刷新页面的情况下提交表单?