返回JSON格式PHP/AJAX的问题
目前,我正在构建自己的MVC,试图更好地理解现有框架的基本原理。然而,我遇到了一个问题,我有一个ajaxget方法,试图将返回的数据输出到JSON中。以下是PHP和Javascript:返回JSON格式PHP/AJAX的问题,php,jquery,ajax,Php,Jquery,Ajax,目前,我正在构建自己的MVC,试图更好地理解现有框架的基本原理。然而,我遇到了一个问题,我有一个ajaxget方法,试图将返回的数据输出到JSON中。以下是PHP和Javascript: public function ajaxGet(){ $stat = $this->db->prepare("SELECT * FROM data"); $stat->setFetchMode(PDO::FETCH_ASSOC); //fetch the data as an
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
});
$(函数(){
$.get(“/mvc2/dashboard/ajaxGet”,函数(o){
console.log(o);//出于某种原因,我不得不删除“json”以使其正常工作??
对于(var i=0;i,您可以在响应中提供适当的HTTP头:
...
header('Content-type: application/json');
echo json_encode($data);
或者您使用$.getJSON()
而不是$.get()
尝试以下方法:
PHP:
JS:
如果不使用控制台,请务必注释掉任何console.log
方法
在AJAX调用的回调中,检查console.log。您的o
是返回的数据对象。因此,您需要从PHP结果中使用类似o.colName
的内容访问属性
确保你的MVC路径是正确的,我相信你说这是因为你看到了某种数组
在回显json字符串之前,请尝试发送如下标题:header('Content-type:application/json');
显示console.log(o)的结果
。恐怕其中一个或两个都不走运:/。不过感谢您的快速响应。您不需要内容类型,这只是一个很好的实践。在$.get中,他的第三个参数是“json”-它指定自动解析json。嗨,我恐怕还是不走运。但是,是的,我知道您的意思。我将o传递给它自己并记录下来,因为我想将所有返回的数据作为一个对象来查看。但它没有记录任何内容。使用say o[0]来定义它.id立即返回。路径正确,我可以在Chrome中的网络资源中看到返回的数据。下面是我的意思:该数组不是来自json\u encode
-它是恶意的,正在破坏您的脚本。在您找出print\u r
调用的位置后,对其进行注释并再次测试。在您的JS中,您可以然后用$遍历您的结果。每个(o,函数(i,v){console.log(v.id,v.data);});
所以这可能就是问题所在,我将如何着手解决它?谢谢,我将尝试一下。
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
}