目前我正在构建自己的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返回。但没有任何数据被记录或提醒。
试试这个:
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:
- 如果您不使用控制台,请务必注释掉任何
console.log
方法 - 在AJAX调用的回调中,检查console.log。您的
o
是返回数据的OBJECT。。话虽如此,您需要从PHP结果中使用类似o.colName
的东西来访问属性 - 确保你的MVC路径是正确的,我相信你说这是因为你看到了排序的数组
要么在响应中提供正确的HTTP标头:
...
header('Content-type: application/json');
echo json_encode($data);
或者使用$.getJSON()
而不是$.get()
。