简体   繁体   English

使用AJAX从PHP脚本获取JSON数据

[英]Getting JSON data from a PHP script using AJAX

My PHP script, 'getNews.php', (which works when I run it in the terminal and returns the correct data) is as follows: 我的PHP脚本“ getNews.php”(当我在终端中运行它并返回正确的数据时可以使用)如下:

<?php
header('Content-Type: application/json');

$db = new PDO('mysql:host=hostname;dbname=table', 'name', 'password');

$sql = "SELECT * from `news` ORDER BY date";
$result = $db->query($sql);

echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
?>

In my Javascript (I have JQuery loaded), I am attempting to pull this data in the following manner: 在我的Javascript(已加载JQuery)中,我尝试通过以下方式提取此数据:

$(document).ready(function() {
    $.getJSON("getNews.php", function(data) {
        console.log(data);
    });
});

which does nothing. 什么都不做。 When I change it to: 当我将其更改为:

$(document).ready(function() {
    $.get("getNews.php", function(data) {
        console.log(data);
    });
});

It writes the entire text of the php script to the console. 它将php脚本的整个文本写入控制台。 Basically, it doesn't seem to be executing the php script or retrieving the json object at all. 基本上,它似乎根本不执行php脚本或检索json对象。 Thoughts? 有什么想法吗?

Do you have a web server (like or ) installed? 您是否安装了Web服务器(如 )? "It writes the entire text of the php script to the console." “它将php脚本的整个文本写入控制台。” = You aren't invoking a PHP processor. =您没有调用PHP处理器。 Are you loading it like file:///something , or via http://something ? 您是像file:///something还是通过http://something加载它?

If you are using HTTP, make sure your web server knows to process PHP files. 如果使用的是HTTP,请确保您的Web服务器知道要处理PHP文件。 This usually involves editing a .ini or .cfg file; 这通常涉及编辑.ini或.cfg文件; I can't tell which, because you don't mention what web server you are using. 我不知道是哪个,因为您没有提到您使用的是哪种Web服务器。

It writes the entire text of the php script to the console 它将php脚本的整个文本写入控制台

It could be that your server doesnt have php installed/configured. 可能是您的服务器没有安装/配置php。 If thats not the case then see if this works for you 如果不是这种情况,那么看看是否适合您

function prsJSN() {
    $.ajax({
        type: "get",
        url: "getNews.php",
        success: function(json) {
            var dataArray = jQuery.parseJSON(json);
        },
        error: function(request, status, error) {
            alert(request.responseText);
        }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM