ajax调用返回NULL

时间:2020-03-24 23:02:09

标签: php json ajax

我正在玩AJAX呼叫。我尝试将数据传递到sql查询,并在我的JS文件中接收回数据。错误函数总是在JavaScript中调用错误函数

XHR标头在预览中返回此值:Array ( [address] => Street 12 [name] => twelve [id] => 12 [surname] => twelve )

文件data_3.php

<?php
require 'assets/external/db.php';
$data =  file_get_contents('php://input');
$data = json_decode($data, true);

$id = $data['id'];

$queryData = $mysqli->prepare("
SELECT
    id
FROM
    listing
 WHERE id = ?
");
$queryData->bind_param('s', $id);
$queryData->execute();
$data = $queryData->get_result();

$data = mysqli_fetch_all($data, MYSQLI_ASSOC);
mysqli_close($mysqli);
echo json_encode($data);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript" src="assets/js/json_test.js"></script>

<script>
    var ajaxData = {
        "address": "Street 12",
        "name": "twelve",
        "id": 12,
        "surname": "twelve"
    };
    loadData('assets/external/data_3.php', ajaxData);
</script>

文件json_test.js

function loadData(url, ajaxData) {
console.log('JS loaded');
$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(ajaxData),
    async: false,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (results) {
        console.log(results);
    },
    error: function (e) {
        console.log(e);
    }
});
}

如何正确调用sql查询,以便填充$ id并将结果返回到JS函数loadData?

1 个答案:

答案 0 :(得分:0)

通过将sql部分拆分为新文件解决的问题