douliang1891 2013-06-28 02:52
浏览 55

如何从jquery php调用类函数?

I'm working with the plugin ParamQuery grid and to the data source need to get json data, this what I want to do with $. getJson (...) {}, but I have a PHP class called data.php, which contains a method called GetData other InsertData, DeleteData, (CRUD-using PDO), GetData returns the infromacion as json. The problem is how to call the function from jquery?

the code I use is:

data.php

   <?php
   class Data {
   private $db = NULL;
   const DB_SERVER = "localhost";
   const DB_USER = "root";
   const DB_PASSWORD = "usbw";
   const DB_NAME = "musicstore";

   public function __construct() {
    $dsn = 'mysql:dbname=' . self::DB_NAME . ';host=' . self::DB_SERVER;
    try {
        $this->db = new PDO($dsn, self::DB_USER, self::DB_PASSWORD);
    } catch (PDOException $e) {
        throw new Exception('Connection failed: ' . $e->getMessage());
    }
    return $this->db;
   }

    public function getData() {

    $statement = $this->db->prepare("Select * from Customer");
    $statement->execute();

    if ($statement->rowCount() > 0) {
        echo json_encode($statement);
    }

    return false;
     }
   }
 ?>

functionjquery.js

    $.getJSON('Data.php', function(data) {
var obj = {};
obj.width = 1000;
obj.height = 400;
obj.colModel = [{title: "Rank", width: 150, dataType: "integer"},
    {title: "Company", width: 200, dataType: "string"},
    {title: "Revenues ($ millions)", width: 200, dataType: "float", align: "right"},
    {title: "Profits ($ millions)", width: 200, dataType: "float", align: "right"}];
obj.dataModel = {data: data};
$("#grid_array").pqGrid(obj);

});
  • 写回答

2条回答 默认 最新

  • dtot74529 2013-06-28 02:59
    关注

    You need to create a page which constructs an instance of the Data class and then outputs the results of getData()

    You shouldn't be echoing from inside a function though. Change your getData method to something like the following:

    public function getData() {
        $statement = $this->db->prepare("Select * from Customer");
        $statement->execute();
        return $statement->rowcount() > 0 ? $statement->fetchAll() : NULL;
    }
    

    Then, create a new page let's call it json_data.php for transparency's sake:

    require_once "data.php";
    $dataObj = new Data();
    echo json_encode($dataObj->getData());
    

    Now change your $.getJSON call in jQuery to request the json_data.php page.

    $.getJSON('json_data.php', function(data) { ... });
    

    And that should work.

    评论

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测