如何保留段落格式从php传递字符串到javascript

时间:2017-02-14 14:18:38

标签: javascript php mysql

好的,我们走了。我从MySQL表数据中提取字符串列表,如下所示:

1 Lumbar facet syndrome, bilateral
2 Bilateral knee arthropathy
3 Bilateral hip arthropathy
4 Right shoulder arthropathy, posttraumatic,
5 Chondromalacia of patella
6 Diabetes mellitus with diabetic nephropathy
7 Lower back pain
8 OA

我想保留此格式,因为我需要将此信息放入文本框中。

我正在使用的程序有一个插件系统,允许系统将javascript注入表单页面。所以插件看起来像这样

 function newForm_javascript_onload() {

     //This part grabs the data from the MySQL table. 
    $sql = "SELECT dictation FROM form_dictation WHERE id = ? ORDER BY date DESC LIMIT 1";
    $stmDia = array($id);
    $list = sqlQuery($sql,$stmDia);
    $list = $list['dictation'];

     //Here I chop out the part of the text that I need for the text box
    $diaBegin = strpos($list, "Active Problems") + 26;
    $diaEnd = strpos($list, "Plan") - 4;
    $diaLength = strlen($list);
    $diaChop = ($diaEnd - $diaLength); 
    $diaNar = substr($list, $diaBegin, $diaChop);


    //This is the part that gets injected into the page
    echo "
         var diagnoses = '$diaNar';  //This is where formatting breaks the code

         //This part should populate the textarea

         if(form_diagFac1){
          document.getElementById('form_diagFac1').value = diagnoses;
         }


    ";


  }    

我试过搜索论坛,但没有人发布这样的问题。

我试过var的地方:

var diagnosis  = escape('$diaNar'); //This is where php passes data to java

我知道我可以删除所有格式,以便它显示为段落。

但是,我是否需要创建一个读取每一行的循环?

1 个答案:

答案 0 :(得分:0)

试试json_encode。它将“\ r \ n”添加到字符串而不是新行中,而不会破坏它并将变量作为单个字符串输出。

echo "var diagnoses = " . json_encode($diaNar) . ";