目前我正在构建自己的 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 的函数响应中返回的。但是没有数据被记录或警告。