如何在格式化方法中从PHP方法返回数据到Jquery.Get请求?

时间:2015-06-07 19:53:51

标签: javascript php jquery ajax

刚刚从Asp.net迁移到php。

我正在关注一些教程相关的php mvc。

我目前面临的问题是将数据返回到ajax调用。数据即将发布,但仪表板视图也会附加到它上面。

我的路线设为:

Options -MultiViews
RewriteEngine On
Options -Indexes
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l

RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]

我正在制作jquery请求

$.get('http://localhost:44500/phpmvc/dashboard/xhrGetListItem',function(o){
       console.log(o);
    });

以这种方式回应:

[{"id":"1","text":"hassaan khan"},{"id":"2","text":"we are working fine by the way and all is good hope you all are good too"},{"id":"3","text":"\r\n    how day how days are going hope you all working fine"},{"id":"4","text":"\r\n    how day how days are going hope you all working fine"},{"id":"5","text":"i am doing some thing extremely good. know that\r\ni am working on php.\r\n    "}]
<html>
    <head>
        <title>Test</title>
        <link rel="stylesheet" href="http://localhost:44500/phpmvc/public/css/default.css" />
        <script type="text/javascript" src="http://localhost:44500/phpmvc/public/js/jquery-1.11.3.min.js"></script>
        <script type="text/javascript" src="http://localhost:44500/phpmvc/public/js/custom.js"></script>
        <script type="text/javascript" src="http://localhost:44500/phpmvc/views/dashboard/js/default.js"></script>
        <script type="text/javascript">
        $(document).ready(function(){
         //Custom Functions here
        })
    </script>
    </head>
    <body>
        <div id="header">
        Header

            <br />
            <a href="http://localhost:44500/phpmvc/index">Index</a>
            <a href="http://localhost:44500/phpmvc/help">Help</a>
            <a href="http://localhost:44500/phpmvc/dashboard/logout">Logout</a>
        </div>
        <div class="content">
        Content



dashboard ... logged in


            <br/>
            <form id="dashForm" action="http://localhost:44500/phpmvc/dashboard/xhrInsert" method="post">
                <textarea rows="4" cols="50" name="text"></textarea>
                <input type="submit"/>
            </form>
            <br/>
            <hr/>
            <div id="listInsert"></div>
        </div>
        <hr />
        <div id="footer">
    &copy; Footer
</div>
    </body>
</html>

正如您所见,Dashboard页面/视图html也在数据成功中返回

我已将仪表板控制器功能设置为:

 function xhrGetListItem(){
    //$this->model Dashboard Model object initialized in constructor
    //calling model method 
    $this->model->xhrGetListComment();
    }

在Dashboard Model中我有方法定义

function xhrGetListComment(){
        //$this->db get the database object
        $sth = $this->db->prepare('SELECT * FROM data');
        $sth->setFetchMode(PDO::FETCH_ASSOC);    
        $sth->execute();  
        $data = $sth->fetchAll();
        //print(json_encode($data));
        echo json_encode($data);            
    }

我如何只返回json对象?

0 个答案:

没有答案