문제

Ok, so I am using a combination of cakephp 1.2, jquery, and ajax with JSON. Here is what I'm doing:

When a person inputs an employee id, I get the result of that employee id, if there is one, and I send it back as a $javascript->object(empInfo). This works fine. I am returning the information to the function, but I can't seem to process it. Everything I have read says to use it as $.each(empInfo, function(). Here is my code:

COMMON.JS

$(document).ready(function() {
$('#emp_num').blur(function() {
        if($(this).val().length != 0) {
            $.ajax({
                type: "POST",
                datatype: "json",
                url: '/ir_employees/getdetails/empId:' + $(this).val(),
                success: function(empInfo) {
                    populateEmployeeInformation(empInfo);
                }
            });
        }
    });
});

function populateEmployeeInformation(empInfo) {
    $.each(empInfo, function() {
        console.log(this);
    });
}

EMPLOYEES_CONTROLLER.PHP

function getdetails() {
    $empId = $this->passedArgs['empId'];
    $this->layout = 'ajax';
    $this->set('empInfo', $this->IrEmployee->find('all', 
                        array('conditions' =>
                                array('IrEmployee.employee_number' => $empId))));

}

GETDETAILS.CTP

<?php
    if((isset($empInfo))){
        echo $javascript->object($empInfo);
    }

?>

When I log it, I get the following (screenshot):

JSON Screen Capture

How can I use the following information properly (this is the "response" from Firebug):

[{"IrEmployee":{"id":"1","employee_number":"xxxxx","last_name":"Doe","first_name":"John","gender":"M","date_hired":"2013-04-09","date_of_birth":"1950-01-01","plant_id":"0"}}]
도움이 되었습니까?

해결책

Your response is being returned as a string (console.log shows you're looping through each character of the string), and is not being parsed as JSON.

I think this is because you have datatype instead of dataType (note the uppercase T) in the jQuery AJAX options. If you fix this, jQuery should automatically parse the JSON for you.

Alternatively, you could pass the string into JSON.parse (if it exists, if not you should polyfill)

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top