我一直在尝试使用 jquery .ajax 函数从服务器获取数据。 但是,每当我将数据类型指定为 JSON 时,它都不起作用。
当我没有定义 dataType 时它工作正常,但我需要 dataType 是 JSON..
下面是代码。
Practice.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Practice</title>
<?php
require("db.php");
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div>Why doesn't it work..</div>
<div id="demo"></div>
<button type="button" id="button" name="button">button</button>
</body>
<script>
//Load table
$('#button').on('click', function(){
// var please = 1;
$.ajax({
type: 'POST',
url: 'AJAX.php',
// data: {id: please},
dataType: 'json',
success: function(data) {
$('#demo').text('Worked!');
console.log(data);
},
error: function(error) {
$('#demo').text('Error : ' + error);
console.log(error);
}
});
});
</script>
</html>
AJAX.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Ajax Practice</title>
<?php
require("db.php");
?>
</head>
<body>
<?php
if (isset($_POST["id"])) {
$id = $_POST["id"];
} else {
$id = 1;
}
$stmt = $conn->prepare("SELECT * FROM projects WHERE id=$id");
$stmt->execute();
$all = $stmt->fetchAll(PDO::FETCH_ASSOC);
$all = json_encode($all);
echo $all;
?>
</body>
</html>
这是 echo 的结果..
[
{
"Project":"BPM",
"Date":"2018-03-02 00:00:00",
"Manager":"Someone",
"Status":"2",
"ID":"1",
"Counter":null
}
]
我对 Jquery 和网络编程还很陌生。 请告知,非常感谢您的帮助。
最佳答案
从 AJAX.php 中删除所有 HTML,然后将下面的代码添加到 AJAX.php 的顶部
header('Content-Type: application/json');
关于javascript - Jquery AJAX 不从 PHP 文件中获取 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48678530/