开发者

JSON object "undefined" error in Javascript

I am uploading a file using PHP and want to return the file name and the file status to javascript. In PHP I create the json object by:

$value = array('result' => $result, 'fileName' => 开发者_StackOverflow中文版$_FILES['myfile']['name']);   
print_r ($value);
$uploadData = json_encode($value);

This creates the json object. I then send it to a function in javascript and recieve it as a variable called fileStatus.

alert (fileStatus);

It displays

{"result":"success","fileName":"cake"}

which should be good. But when I try and do

fileStatus.result or fileStatus.fileName 

I get an error saying that they are undefined. Please help I'm really stuck on this. Thanks.


The fileStatus is just a string at this point, so it does not have properties such as result and fileName. You need to parse the string into a JSON object, using a method such as Firefox's native JSON.parse or jQuery's jQuery.parseJSON.

Example:

var fileStatusObj = jQuery.parseJSON(fileStatus);


If the alert displays {"result":"success","fileName":"cake"} then you probably still have to turn the string into a JSON object. Depending on the browsers you are developing for you can use the native JSON support or the JSON.org implementation to turn your string into an object. From there on it should work as expected.


When you are setting the variable, do not put quotes around it. Just set the variable like this:

var fileStatus = <?php echo $uploadData; ?>;

or:

var fileStatus = <?=$uploadData?>;

Do not do this:

var fileStatus = '<?php echo $uploadData; ?>';
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜