0

目前我正在构建自己的 MVC,以尝试更好地理解现有框架的基本原理。但是,我在使用 AJAX get 方法并尝试将返回的数据输出到 JSON 时遇到了问题。下面是 PHP 和 Javascript:

public function ajaxGet(){
    $stat = $this->db->prepare("SELECT * FROM data");
    $stat->setFetchMode(PDO::FETCH_ASSOC); //fetch the data as an associative array
    $stat->execute();
    $data = $stat->fetchAll();
    echo json_encode($data);
    //since we are passing the data from a json encoded ajax request
    //we must format it that way here
}

下面是我的javascript。

$(function(){

$.get("/mvc2/dashboard/ajaxGet", function(o){

    console.log(o); //for some reason i had to remove 'json' to get this to work??
    for(var i=0;i<1;i++){

        $('#listInserts').append('<div>'+o+'</div><br>');
    }

    }, 'json'); 
    //output in json format


$('#accountInsert').submit(function(){

    var url = $(this).attr('action');
    //this gets the value of action in our form
    //so we can pass all the data and hadle the request from there 
    var data = $(this).serialize(); 
    //The serialize() method creates a URL encoded text string by serializing form values.
    $.post(url, data, function(o){
        //post the url and the data
        //and have a call back function called 'o'
        console.log(url, data);
    });

    return false; 
    //return flase so the form data can be handled
    //through javascript
    //and so we don't refresh the page
});

});

现在请注意,当我从我的 javascript 函数中删除“json”标签时,数据会输出一个关联数组,即使有标签,我也可以看到数据是在 chrome 的函数响应中返回的。但是没有数据被记录或警告。

4

2 回答 2

0

您可以在响应中提供正确的 HTTP 标头:

...
header('Content-type: application/json');
echo json_encode($data);

或者您使用$.getJSON()而不是$.get().

于 2013-07-02T16:47:08.273 回答
0

尝试这个:

PHP:

public function ajaxGet(){
    $stat = $this->db->prepare("SELECT * FROM data");
    $stat->execute();
    $data = $stat->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($data);
    //since we are passing the data from a json encoded ajax request
    //we must format it that way here
}

JS:

  1. console.log如果您不使用控制台,请务必注释掉任何方法
  2. 在 AJAX 调用的回调中,检查 console.log。您o是返回的数据的对象.. 话虽如此,您需要使用o.colNamePHP 结果中的内容访问属性。
  3. 确保您的 MVC 路径是正确的,我相信您说这是因为您看到了一个排序数组。
于 2013-07-02T16:56:21.163 回答