开发者

Strange JSON behaviour, scope of a javascript variable

开发者 https://www.devze.com 2023-02-12 04:04 出处:网络
I have an array in a php variable called $result. When I do echo json_encode($result); I get: [{\"id\":\"4\",\"rank\":\"adm\",\"title\":\"title 1\"},

I have an array in a php variable called $result.

When I do echo json_encode($result); I get:

[{"id":"4","rank":"adm","title":"title 1"},
{"id":"2","rank":"mod",,"title":"title 2"},
{"id":"5","rank":"das","title":"title 3"},
{"id":"1","rank":"usr""title":"title 4"},
{"id":"3","rank":"ref","title":"title 5"}]

However I get a different result when try to get same using alert. Here is the example.

<script type="text/javascript">
//<![CDATA[
$(document).ready(function() { myArray = <?=json_encode($result);?>; });
$('img.delete').click(function() { alert(myArray); }
//]]>
</script>

The alert that I get is [object开发者_如何学运维 Object],[object Object], ...

I am not sure, but it seems that the variable myArray is not properly getting carried to $('img.delete').click(function().


Invoking alert(myArray) doesn't give you the json representation of your data. The function alert() invokes toString() on its argument. And the default toString() implementation of an javascript object just returns the string "[object Object]".

If you want to display the JSON representation, then you can use a json serialization library to generate the json string. This page explains an example.


It seems to me that you have an array of objects, in the JS I would say you need to itterate through the objects and read the variables within, as the alert isn't displaying the contents of the object onthat that you've asked to show whats in the array - which is to say: and array of objects.

I would save the array to variable and itterate through the array and then output the array contained within for each.

um.... kinda like this:

for(i = 0; i < myArray.length; i++) {
 // access each sub object and collate the info you want to display
 // ie: myArray[i]['id']
}

I may have over-simplified it, but i can remember having the same issues with an ajax app i built and im sure this is the way i went about it.


What would you expect?

Try echo array("1" => 1, "2" => 2); in php and see what you get.

myArray is a javascript object, not a string that you can easily output. If you want to output a certain value, then write alert(myArray[0]['id']);

The other thing - variable scope. You should declare myArray as a global if you want to use it in various closures.

0

精彩评论

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