簡體   English   中英

無法從PHP文件接收js ajax請求中的json

[英]cannot receive json in js ajax request from php file

onclick到一個按鈕上,js啟動對php文件的ajax請求。 然后,php文件使用php-loop獲取數據庫的一個表的所有條目。 將它們添加到數組中,然后php文件將其解析為JSON,並將其回顯給ajax請求。 成功時,ajax請求應該輸出警報,但是我既不會收到錯誤,也不會收到警報。

根據評論添加一些更改之后。 現在它隨機顯示錯誤消息2錯誤消息:

Fehler: {"readyState":0,"responseText":"","status":0,"statusText":"error"}


Fehler: {"readyState":4,"responseText":"<br />\n<b>Fatal error</b>:  Uncaught Error: Cannot use object of type mysqli_result as array in C:\\xampp\\htdocs\\integration\\get.php:32\nStack trace:\n#0 C:\\xampp\\htdocs\\integration\\get.php(13): getLevel1()\n#1 {main}\n  thrown in <b>C:\\xampp\\htdocs\\integration\\get.php</b> on line <b>32</b><br />\n","status":200,"statusText":"OK"}

php請求(故意保留mysqli屬性):

    $func = $_POST['func'];

if ($func == "getLevel1"){
    getLevel1();
}

$result = array();

function getLevel1(){
    // Create connection
    $conn = new mysqli(servername, username, password, dbname);
    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $sql = "SELECT id, name FROM capability_level1";
    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
            $result[] = '<button onclick="capability('. $row["id"] .')">' . $row["name"]. '</button></br>';
        }
        echo json_encode($result);
    } else {
        echo json_encode("0 results");
    }
    $conn->close();
}

js ajax調用:

async function getLevel1() {
    return $.ajax({
        type: "POST",
        dataType: "json",
        url: "get.php",
        data: {
            func: "getLevel1"
        },
        success: function(data) {
        alert(JSON.stringify(data));
        console.log(data);
        },
        error: function(data) {
        alert("Fehler: "+ JSON.stringify(data));
        }
    });
}

當您有一個完整的數組要編碼時,需要放置json編碼:while之后:

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $result[] = '<button onclick="capability('. $row["id"] .')">' . $row["name"]. '</button></br>';

    }
    echo json_encode($result);
} else {

還要注意,您可能必須將數據類型更改為Json(並將json發送到php)才能返回它。 實際上,您的Ajax正在等待文本返回(基於數據類型)

對於您的進一步錯誤:這與您使用錯誤的函數從mysql獲取行有關。 有關如何修復此問題的更多詳細信息,請參見此問題

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM