javascript - Jquery AJAX 不从 PHP 文件中获取 JSON

标签 javascript php jquery json ajax

我一直在尝试使用 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/

相关文章:

javascript - 为什么 $.appendTo() 没有正确附加我的 <options> 标签?

javascript - DOMParser 在 IE9 中未定义

javascript - 在 innerText 中加粗一个词

javascript - 将数据发布到 JsonP

javascript - ASP.NET MVC Razor <text> 标签不接受小于或等于运算符

php - 创建交易后更新 Memberpress 到期日期

php - fatal error : Call to a member function fetchAll

jquery - jquery datatable sDom的含义和用法是什么?

php - 如何从laravel中的mysql存储过程中获取多个结果集

javascript - 语义 UI 将初始化为下拉菜单的选择恢复为常规 HTML 选择菜单