iT邦幫忙

0

請益 透過ajax進到後端資料庫撈資料,但無法顯示在前端

小弟我最近在學習網頁語法,想透過ajax執行不跳頁就能刷新部分區塊內容
資料有撈出來(在Newtork有看到資料),但無法顯示在前端上
卡了4天 還是想不透,決定上來發問 還請各位大神鞭小力一點/images/emoticon/emoticon02.gif

以下是程式碼
#html

<!DOCTYPE html>
<html lang="en">
    
<head>
    <title>歷史查詢</title>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/php_stock/css/Search.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
    <div class="header">

    </div>
    <form id="demo">
        <div class="Select">
            <h2>查詢</h2>
            <table id="Select">
                <tr>
                    <th>ID</th>
                    <th>Codename</th>
                    <th>Name</th>
                    <th>Buy_Sell</th>
                </tr>
                <tr>
                    <td><input type="text" id="ID" name="ID" placeholder="請輸入ID"></td>
                    <td><input type="text" id="Codename" name="Codename" placeholder="請輸入代號"></td>
                    <td><input type="text" id="Name" name="Name" placeholder="請輸入名字"></td>
                    <td><button type="button" id="btn">送出</button></td>
                </tr>
            </table>
        </div>
    </form>
    <p id="result"></p>
    
    <script>
        $(document).ready(function() {
            $("#btn").click(function() { //ID 為 submitExample 的按鈕被點擊時
                $.ajax({
                    type: "POST", //傳送方式
                    url: "../php/Search.php", //傳送目的地
                    dataType: "json", //資料格式
                    data: { //傳送資料
                        ID: $("#ID").val(),
                        Codename: $("#Codename").val(),
                        Name: $("#Name").val()
                    },
                    success: function(data) {
                        if (data.ID != null) { //如果後端回傳 json 資料有 ID
                            $("#demo")[0].reset(); 
                            $("#result").html(data.ID +data.Codename + data.Name);
                        } else { //否則讀取後端回傳 json 資料 errorMsg 顯示錯誤訊息
                            $("#demo")[0].reset(); 
                            $("#result").html('<font color="#ff0000">' + data.errorMsg + '</font>'+ '錯誤!!');
                        }
                    },
                    error: function(jqXHR) {
                        $("#demo")[0].reset();
                        $("#result").html('<font color="#ff0000">發生錯誤:' + jqXHR.status + '</font>'+ '爆了直接error');
                    }
                    
                })
            })        
        });
        
    </script>
</body>
</html>

#php

<?php
session_start();
include("SQLFunction.php");

header('Content-Type: application/json; charset=UTF-8'); //設定資料類型為 json,編碼 utf-8
    $ID = $_POST["ID"]; //取得 ID POST 值
    $Codename = $_POST["Codename"]; //取得 Codename POST 值
    $Name = $_POST["Name"]; //取得 Name POST 值
    if ($ID!= null || $Codename!= null || $Name!= null) { //如果 ID,Codename,Name  都有填寫
        $Sear_Stock = Search_Stock($ID, $Codename, $Name);
        echo json_encode($Sear_Stock);
    } else {
        //回傳 errorMsg json 資料
        echo json_encode(array(
            'errorMsg' => '資料未輸入完全!'
        ));
    }

?>

#SQL語法

function Search_Stock($ID){
    global $ConnectSystem;
    $sql = ("SELECT * 
            FROM `stock`.`history` 
            WHERE `ID` = :ID ");
    $sth = $ConnectSystem -> prepare($sql);
    $sth ->bindParam(":ID", $ID, PDO::PARAM_INT);
    $sth ->execute();

    $Sear_Data = array();
    while($Result = $sth -> fetch(PDO::FETCH_ASSOC)){
        $Sear_temp['ID'] = $Result['ID'];
        $Sear_temp['Date'] = $Result['Date'];
        $Sear_temp['Codename'] = $Result['Codename'];
        $Sear_temp['Name'] = $Result['Name'];
        $Sear_temp['Buy'] = $Result['Buy'];
        $Sear_temp['Quantity'] = $Result['Quantity'];
        $Sear_temp['Price'] = $Result['Price'];
        $Sear_Data[] = $Sear_temp;
    unset($Sear_temp);
    }
    return $Sear_Data;
}

###在Network 點副檔名(php)有看到資料被撈出來
unsplash 圖片
在Network查看Search.php 有撈到資料 也是json格式
但,就會卡在Script的success else

目前猜測是格式問題,但不知道該如何修改

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

2 個回答

2
japhenchen
iT邦超人 1 級 ‧ 2021-07-13 08:29:56
最佳解答

問題出在success裡,你的data是陣列,所以你data.ID必定=== null
(在javascript中請改掉只用==、!=的習慣,要改成===、!==)

success: function(data) {
    data.forEach(function(v){  
        // 把data foreach成 v(alue)
        // 或用for(i=0,i<data.length;i++) let v = data[i]
        
        
        if (v.ID != null) { //如果後端回傳 json 資料有 ID
            $("#demo")[0].reset(); 
            $("#result").html(v.ID +v.Codename + v.Name);
        } else { //否則讀取後端回傳 json 資料 errorMsg 顯示錯誤訊息
            $("#demo")[0].reset(); 
            $("#result").html('<font color="#ff0000">' + v.errorMsg + '</font>'+ '錯誤!!');
        }
    }
}

非常感謝您的回答,想請問 php已經使用json_encode,為什麼script裡面的data會是陣列?

因為你從資料庫撈出來的資料不是單筆資料,所以就是陣列

// 這是把所有指針全部跑一遍不是嗎?
while($Result = $sth -> fetch(PDO::FETCH_ASSOC))

了解 謝謝!!

1
screenleon
iT邦新手 1 級 ‧ 2021-07-13 08:30:06

你收到的data 他是array的型態
你可以嘗試 console.log(data[0].ID)取的你要的ID值
其他類推

我要發表回答

立即登入回答