0

如何修复此未终止的字符串文字错误。此错误是什么意思以及如何修复

以下是完整代码:

    <?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;
    }​
4

2 回答 2

2

这意味着您的引号有问题(回显内容中的额外单引号或换行符)并且它弄乱了解析器。确保正确转义 JS 中的任何特殊字符(引号、换行符等)。

json_encode为你做这个。

于 2012-04-28T23:13:33.073 回答
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它将是一个包含单个元素的数组,而当您不发布表单时,它将是一个空数组。其余的逻辑应该像以前一样工作,但请阅读我添加的评论。

于 2012-04-29T12:56:29.460 回答