Что ж, у меня проблема с чтением данных JSON в jQuery, который выводится PHP, я уже использую json_encode();
<?php
require_once 'Post_db.php'; // a Class for doing MySQL work
/* the Post class */
class Post {
/* An array that stores the post item data: */
private $pdata;
/* The constructor */
public function __construct($postData){
if(is_array($postData))
$this->pdata= $postData;
}
public function __toString(){
// The string that is beeing returned
// is outputed by the echo statement
$toBeJsoned=$this->pdata;
$toBeSent=json_encode($toBeJsoned);
return $toBeSent;
}
//read the Posts
public static function readPosts(){
$query = new Post_db("SELECT * FROM pmessage
ORDER BY p_id DESC
");
$posts = array();
while($row = $query->fetchRow()){
$posts [] = new Post($row);
}
foreach($posts as $item){
echo $item;
}
}
Теперь Jquery:
Этот кодчитает, но это только $.get
метод.И он возвращает myPosts
как 1 массив с около 5000 elmenets, но есть только около 50 сообщений, поэтому он получает каждый символ из этой строки как элемент массива.
function readMyPosts(){
$.get("phpFileThatCalltheFunctionsToRead.php",
{"action": "autoRead"},
function(myPosts){
//a ul element
$("#plist").html("<li>"+myPosts+"</li>");
});
}
readMyFacts();
Когда я пытаюсь с $.ajax
или $.getJSON
, я никогда не достигаю функции успеха, на самом деле ничего не происходит
function ReadNewestFacts(){
$.ajax({
url:"phpFileThatCalltheFunctionsToRead.php",
data:"action=autoRead_main",
dataType:"json",
success: function(json){
//do something with the data
alert(json);
}});
}
//run this function
ReadNewestFacts();
Файл phpFileThatCalltheFunctionsToRead.php
выглядит так:
<?php
session_start();
require_once "post.class.php";
if(isset($thisUid)){
$thisUid= $_GET['thisUid'];
}
if(isset($action)){
$action = $_GET['action'];
}
try{
switch($_GET['action'])
{
case 'autoRead_main':
Post::readPosts();
break;
case 'autoRead':
Post::readMyPosts($_GET['thisUid']);
break;
case ' more cases
..
.
.
.'
}
}
catch(Exception $e){
// echo $e->getMessage();
die("0");
}
Все, что мне удалось получитьis
{"p_id":"1","p_text":"blabla","p_adder":"1"}{"p_id":"2","p_text":"blabla2","p_adder":"1"}{"p_id":"3","p_text":"more blabla","p_adder":"2"}{"p_id":"4","p_text":"more and more blabla","p_adder":"1"}{}....
Форматирование JSON, кажется, работает правильно! ?, но я думаю, что Jquery не может прочитать строку JSON из PHP?Я действительно не уверен здесь :( ..
Я не в состоянии получить доступ к данным JSON на стороне jQuery .. Я перепробовал много методов, найденных здесь, на StacKover .. но я думаю, что я что-то упустил..