How to echo json object without being wrapped in quotes?
First time dealing with json. I have a php file that processes the post vars sent to it via ajax and then it will echo back a json_encoded array. I cannot iterate thru it because it's wrapped in double quotes. How I do get around this?
The jquery code:
$j.ajax({
type: 'GET',
url: 'http://example.com/doaction.php',
data: 'num=' + fileNum[1],
success: function(jsonobj) {
for (var key in jsonobj) {
if (jsonobj.hasOwnProperty(key)) {
var jsonob = jsonobj[key];
console.log(key + " = " + jsonob);
}
}
}
});
The php code in doaction.php:
if ($_GET['num']) {
$meta = file_meta($_GET['num']); // returns an array
echo json_encode($me开发者_如何学Cta);
}
file_meta function:
function file_meta($num = 1) {
$num = '_' . $num;
$meta = array(
'filename' . $num => array(
'value' => ''),
'link' . $num => array(
'value' => ''),
'description_' . $num => array(
'value' => ''),
'metadata' => array(
'type' => 'checkbox',
'label' => 'Indicate applicable competencies:',
'items' => array(
'core_teaching' . $num => array(
'label' => 'Core Teaching',
'value' => 0
),
'teaching_learning' . $num => array(
'label' => 'Teaching Learning',
'value' => 0
),
'instructional_design' . $num => array(
'label' => 'Instructional Design',
'value' => 0
),
'assignment_and_evaluation' . $num => array(
'label' => 'Assignment & Evaluation',
'value' => 0
),
'research' . $num => array(
'label' => 'Research',
'value' => 0
),
'mentoring' . $num => array(
'label' => 'Mentoring',
'value' => 0
)
)
)
);
return $meta;
}
The result in the console isn't what I was expecting. It should be in key-value pairs but it's gibberish instead like shown below.
500 = ,
501 = "
502 = v
503 = a
.
.
.
I am pretty sure it's because the json object $.ajax()
is getting is wrapped in quotes. When I assign the object
without quotes directly to jsonobj
I get the correct result. When I call file_meta() directly from within the $.ajax()
function I get the correct result:
var jsonobj = <?php $etc = file_meta(); echo json_encode($etc); ?>;
// iterate here...
However that's not what I want because file_meta()
needs to be passed with a value from an element retrieved on click event. And sending it via $_GET is the only I know.
Use json_decode() to convert the JSON string into a PHP variable
$var = json_decode('{"file":{"test": 0}}');
In javascript use:
var decoded = eval('{"file":{"test": 0}}');
If you are using the jQuery library use:
var json = '{"file":{"test": 0}}';
var decoded = $.parseJSON(json);
精彩评论