未确定的字符串文字错误

时间:2012-04-28 23:11:25

标签: php javascript

如何修复此未终止的字符串文字错误。这个错误意味着什么以及如何解决

以下是完整代码:

    <?php
    session_start();

if(isset($_POST['fileImage'])){

$idx = count($_POST ['fileImage']) -1 ;
$output = isset($_POST ['fileImage'][$idx]) ? $_POST ['fileImage'][$idx]['name'] : "";

}

    ?>


    function stopImageUpload(success) {

        var imageNameArray = ['<?php echo  json_encode($output); ?>'];
        var result = '';

        if (success == 1) {
            result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
            for (var i = 0; i < imageNameArray.length; i++) {
                $('.listImage').append(imageNameArray[i] + '<br/>');
            }
        }
        else {
            result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
        }

        return true;
    }​

2 个答案:

答案 0 :(得分:2)

这意味着您的引号出现了问题(echo内容中的额外单引号或换行符)并且它会破坏解析器。确保JS中特殊的任何字符(引号,换行符等)都被正确转义。

json_encode为您做到这一点。

答案 1 :(得分:1)

更好的解决方案可能如下所示:

<?php
session_start();

$results = array();
if(isset($_POST['fileImage'])){
  // not entirely sure what you're trying to achieve here
  // so just replicating the logic you already had
  // but I'm sure there's a better way to do whatever this is trying to do
  $idx = count($_POST['fileImage']) -1 ;
  $results[] = isset($_POST['fileImage'][$idx]) ? $_POST ['fileImage'][$idx]['name'] : "";
}

?>

function stopImageUpload(success) {
  var imageNameArray = <?php echo json_encode($results); ?>;
  var result = '';

  if (success == 1) {
    result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
    for (var i = 0; i < imageNameArray.length; i++) {
      $('.listImage').append(imageNameArray[i] + '<br/>');
    }
  } else {
    result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
  }

  // you might want to use the "result" variable before returning

  return true;
}​

改变了什么?我删除了[]输出周围的json_encode,并用PHP而不是JS创建了数组。这样,当您发布表单时,$results将是一个包含单个元素的数组,如果不这样,它将是一个空数组。其余的逻辑应该像以前一样工作,但请阅读我添加的注释。