iT邦幫忙

0

<form action="xxx.php"> 提交給 php 處理完資料庫也抓回來了

  • 分享至 

  • xImage

各位前輩 不好意思 我很笨

我的需求是
input submit -> xxx.php去資料庫抓資料 -> jquery ajax 接回資料在另一網頁show出

<?php
........
.....
if($_SERVER['REQUEST_METHOD']=='POST'){
 $teacher = $_POST['teacher'];
//echo $teacher;
$requestteacher ="select * from ud where username=:username3";
.....
$found = $stmt3->FetchAll();
echo json_encode($found);

header("refresh:1;'finaltest.html'");
}
?>

最後的那個 header 為了在另一個網頁finaltest.html開起來 show出結果
可是finaltest.html ajax 卻接不到

$(document).ready(function(){
 $.ajax({
                    url:'selectprofile.php',
                    type:'GET',
                    dataType:'json',
                      success: function(data) {..... }
                      ............
                      error: function(){alert(錯誤);}

結果是在finaltest.html中 alert 錯誤

測試過如果上面的selectprofile.php檔
1.$teacher去接 submit過來的值沒問題
2.如果不要用submit 直接給$teacher = '張三三';
不要用 header
下面 jquery 接資料也完全沒問題

目前看起來問題出在
header("refresh:1;'finaltest.html'");
我在猜ajax 在接 .php 傳過來的值得時候接到這行
所以才接不到資料
是我的作法錯誤嗎?
請問我要怎麼接完.php資料後 導向另一個.html頁面 show出資料呢?

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
淺水員
iT邦大師 6 級 ‧ 2022-11-10 15:23:57
最佳解答

方法不少

  1. 利用 session,這是把參數存在伺服器
  2. 利用 localStorage(或 sessionStorage),這是把參數存在瀏覽器
  3. 利用 url 傳遞

另外 header 應該在輸出 body 前使用
也就是說不應該放在 echo 後面
雖然說根據伺服器設定可能仍然能運作,但還是正確使用比較好

localStorage 範例

page1.html

<form id="form1" action="page2.html" method="get">
    <input type="text" name="foo" id="foo" value="測試">
    <input type="submit" value="送出">
</form>
<script>
    //submit 之前,先把資料存在 localStorage
    document.querySelector('#form1').addEventListener('submit', (evt)=>{
        var val = document.querySelector('#foo').value;
        localStorage.setItem('foo', val);
    });
</script>

page2.html

<p id="demo"></p>
<script>
    document.addEventListener('DOMContentLoaded', ()=>{
        //讀取 localStorage 資料
        let fooVal = localStorage.getItem('foo');
        //清除 localStorage 資料
        localStorage.removeItem('foo');
        //顯示(可利用讀取到的資料做其他事,例如 ajax)
        document.querySelector('#demo').textContent = `接收到: ${fooVal}`;
    });
</script>
fufu iT邦新手 5 級 ‧ 2022-11-11 17:18:51 檢舉

問題已經解決
感謝前輩不吝嗇的指教
讓我又學到了一課

我要發表回答

立即登入回答