json_encode 用于多行字符串 php 到 javascript

我正在尝试将一个字符串从 php(来自 mysql)传递到 javascript 中具有多行的变量中。我知道我需要使用 php 的 json_encode() 来做到这一点。它来自 textarea 和 javascript 打开一个小窗口,应该写它的输出。但我似乎无法克服同样的错误:Uncaught SyntaxError: Unexpected end of input


我猜还有其他我需要在 javascript 中做的事情


这是非常简单的js函数:


function view_notes(notes) {

  var myWindow = window.open("", "MsgWindow", "width=400,height=400");


 console.log(notes);

  myWindow.document.write(notes);




}

</script>

这是php:


if ($result = $conn->query($sql)) {


 // echo "regulars <br>";

    /* fetch associative array */

    while ($row = $result->fetch_assoc()) {



      $phone=$row['phone'];

      $formatted_phone=format_phone($phone);

      $notes=$row['notes'];

      $js_notes=json_encode($notes);

      var_dump($js_notes);



      echo"<tr>";

      echo "<td>";

      echo $row['First_Name'];

      echo "</td>";



      //echo "&nbsp";

      echo "<td>";

      echo $row['Last_Name'];

      echo "</td>";

     // echo "&nbsp";



      echo "<td>";

      echo $formatted_phone;

      echo "</td>";

    //  echo "&nbsp";



      echo "<td>";

      echo $row['email'];

      echo "</td>";


      echo "<td>";

      echo $row['court_status'];

      echo "</td>";


      echo "<td>";

      echo "<button onclick=\"view_notes($js_notes)\">View Notes</button>";

      echo "</td>";





      }

      /* free result set */

      $result->free();

  }


红糖糍粑
浏览 177回答 2
2回答

POPMUISE

您没有正确连接字符串。解决替换这条线echo "<button onclick=\"view_notes($js_notes)\">View Notes</button>";和echo "<button onclick='view_notes(".$js_notes.")'>View Notes</button>";要解决换行问题,请再创建一个 javascript 函数function nl2br (str, is_xhtml) {&nbsp; &nbsp; if (typeof str === 'undefined' || str === null) {&nbsp; &nbsp; &nbsp; &nbsp; return '';&nbsp; &nbsp; }&nbsp; &nbsp; var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';&nbsp; &nbsp; return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');}并像这样在 view_notes 函数中使用上述函数function view_notes(notes) {&nbsp; var myWindow = window.open("", "MsgWindow", "width=400,height=400");&nbsp; console.log(notes);&nbsp; myWindow.document.write(nl2br(notes));}

手掌心

你能分享console.log(notes)的结果吗?因为我认为问题是这里的引号不匹配 - echo "View Notes";&nbsp;当它评估它时,它会将 $js_notes 放在双引号中,这会破坏 HTML 语法规则。在浏览器中查看页面的源代码并检查这一行。希望这会有所帮助。
打开App,查看更多内容
随时随地看视频慕课网APP