简体   繁体   English

Javascript中的JSON对象“未定义”错误

[英]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. 我正在使用PHP上传文件,并希望将文件名和文件状态返回给javascript。 In PHP I create the json object by: 在PHP中,我通过以下方式创建json对象:

$value = array('result' => $result, 'fileName' => $_FILES['myfile']['name']);   
print_r ($value);
$uploadData = json_encode($value);

This creates the json object. 这将创建json对象。 I then send it to a function in javascript and recieve it as a variable called fileStatus. 然后我将它发送到javascript函数并将其作为一个名为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 . fileStatus只是一个字符串,因此它没有resultfileName等属性。 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 . 您需要使用诸如Firefox的本机JSON.parse或jQuery的jQuery.parseJSON之类的方法将字符串解析为JSON对象。

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. 如果警报显示{"result":"success","fileName":"cake"}那么您可能仍然需要将字符串转换为JSON对象。 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. 根据您正在开发的浏览器,您可以使用本机JSON支持或JSON.org实现将您的字符串转换为对象。 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; ?>';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM