동적으로 생성 된 HTML 데이터에 PHP를 추가

Ansh Sachdeva :

나는 기본적으로 같은 화면에서 빈 상자에 결과를 클릭 할 특정 PHP 파일을 실행하고 표시합니다 버튼을 많이해야합니다 웹 사이트를 만들려고 노력하고 있습니다. 이 PHP 파일 디렉토리에 존재하는 test_scripts같은 디렉토리에 index.php.

나는 명백한 단계는 해당 파일을 반복하고 동적으로 UI를 생성하는 루프를 만들 수있을 것이라고 생각했다. 그래서 내가 중간에 다음과 같은 PHP 코드를 작성index.php

#Index.php
...
 <?php
            $dir_itr = new DirectoryIterator("test_scripts");
            foreach ( $dir_itr as $file) {
                if ($file->isFile()) {

                    $filename= $file->getFilename() ;
                    $formattedFileName=
                        '<button 
                             class="box button is-large is-fullwidth is-primary is-light" 
                             onclick="loadScriptFileData($filename)">
                                       $filename
                         </button>';
                    print $formattedFileName;
                }
            }
            ?>
...

loadScriptFileData()헤드 스크립트 태그 본 작성된 JS 함수이고

<!--index.php-->

<script>

        function loadScriptFileData(filename) {
            alert(filename);
        }

    </script>

각 루프에 대한 제대로 실행되고 있지만, JS는 기능과 생성 된 HTML이 제대로 작동하지 않습니다. 자신의 페이지에있는 버튼의 예상 수는 있지만, 각 버튼은 단어와 이름이 "$filename"아닌 실제 예상되는 파일 이름을. 이 사건은 똑바로 일을하지 않는 JS와 악화와 같은 consoloe에 오류가 있습니다Uncaught ReferenceError: $filename is not defined at HTMLButtonElement.onclick ((index):71)

왜 $ 변수는 문자열로 변환하기되지 않는 이유는 무엇입니까? 난 있으며, toString () 함수는하지만 여전히 좋은 시도. 내가 잘못을하고있는 중이 야?

kerbholz :

변수는 작은 따옴표를 사용하는 경우 해석 / 구문 분석되지 않습니다.

바꾸다

$formattedFileName= '<button 
  class="box button is-large is-fullwidth is-primary is-light" 
  onclick="loadScriptFileData($filename)">$filename</button>';

$formattedFileName= "<button 
  class=\"box button is-large is-fullwidth is-primary is-light\" 
  onclick=\"loadScriptFileData('$filename')\">$filename</button>";

모든 것이 예상대로 작동합니다.

추천

출처http://10.200.1.11:23101/article/api/json?id=383736&siteId=1