views:

45

answers:

2

I have an ajax response which is an array passed via php's json_encode() function.

Printing it directly to the browser works fine:

for(var i=0; response.length; i++){
    document.write(response[i].text + '<br />');
}

Adding it to a javascript variable throws the error "response[i] is undefined"

var str = '';
for(var i=0; response.length; i++){
    str += response[i].text + '<br />';
}
return str;

I guess I'm confusing the JSON / JS relationship a bit. Is there any way I can use that JSON data in that str variable?

Thanks in advance!

A: 

First, get json2.js

Second, read and adapt:

<script language="javascript">
data = JSON.parse(<?= json_encode($data) ?>);
</script>
Ignacio Vazquez-Abrams
A: 

I have two inline client side solution:

var data = eval('('+ jsonText +')');

or

var data = (new Function("json", "return json;");)(jsonText);
Roki