开发者

problem encoding and parsing json

hi everyone i am fetching some data from a database using php, encoding it as json and then displaying it using ajax whats happening is that inside my json object i have an array which also have json objects...when i try to access the json objects from javascript inside the array i get undefined because they are interpreted as string and not json objects

this is my php code:

<?php

if ($_SERVER['HTTPS'] == 'on') {
    require '../../Objects/Course.php';
    require '../config.php';
    require '../Tools.php';

    $response;

    $c = new Course();
    $courses = listCourses();

    if (is_array($courses)) {
        if (count($courses) != 0) {
            $response = array('result' => true, 'data' => 'exist', 'courses' => '');
            f开发者_Go百科oreach ($courses as $course) {
                $response['courses'][] = json_encode($course);
            }
            print json_encode($response);
        } else {
            $response = array('result' => true, 'data' => 'empty');
            print json_encode($response);
        }
    } else {
        $response = array('result' => false, 'data' => 'empty');
        print json_encode($response);
    }
}
?>

and this is my javascript code:

$.post('ServiceProviders/CourseRelated/listAllCourses.php', function(data){
        if(data.result == true){   
            for(var i = 0 ; i < data.courses.length ; i++){                    
                alert(typeof data.courses[0]);
            }                
        }else{
            alert('something went wrong while listing all the courses...try again later.')
        } 
    },'json');

the output of the alert is string instead of object...how do i fix that ?


Try replacing $response['courses'][] = json_encode($course); with $response['courses'][] = $course; since you only want to json encode your response once.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜