2016-05-13 3 views
1

Заранее за вашу помощь. Мне тяжело держать мою кодовую базу чистой. Я хочу избежать смешения PHP, HTML и CSS.Динамически включать JavaScript из внешнего файла - PHP

В настоящее время мой основной сайт разбит на многочисленные более мелкие вкладки. Код PHP для этих вкладок динамически включается после вызова ajax.

elseif (file_exists('templates/custom/'.$center."/".$section."/".$tab.".php")) { 
include 'templates/custom/'.$center."/".$section."/".$tab.".php"; 
} 

Он отлично работает, но я также хотел бы динамически включать JavaScript из внешнего файла. На мой взгляд, это будет работать, как это,

elseif (file_exists('templates/custom/'.$center."/".$section."/".$tab.".php")) { 
include 'templates/custom/'.$center."/".$section."/".$tab.".php"; 
include 'templates/custom/'.$center."/".$section."/".$tab.".js"; 
} 

Как я могу динамически включать JavaScript основаны на какой вкладке пользователь хочет перейти в то же время сохраняя JavaScript, разделенных вкладке в отдельных файлах.

Я провел весь день, глядя в этот вопрос, и все идут через примеры, которые выглядят так,

echo "<script language='javascript' type='text/javascript'>"; 
echo "alert('hello worldio');"; 
echo "</script>"; 
$URL="page.php"; 
echo "<script>location.href='$URL'</script>"; 

Этот сайт является одной странице приложения. Еще раз спасибо!

ответ

1

Просто print<script> тега, чтобы включить его:

print '<script src="templates/custom/'.$center.'/'.$section.'/'.$tab.'.js'" type="text/javascript"></script>'; 
1

Файлы javascript не могут быть включены функцией php. Используйте приведенный ниже код

elseif (file_exists('templates/custom/'.$center."/".$section."/".$tab.".php")) { 
include 'templates/custom/'.$center."/".$section."/".$tab.".php"; 
$file_path = "javascript external file path"; // replace with correct file path 
?> 
<script language="JavaScript" type="text/javascript" src="<?php echo $file_path;?>"></script> 
<?php } ?> 
+0

Спасибо за Ваш комментарий, но вы можете объяснить, что это делает более подробно? – linuxisthebest33

+0

Выше код используется для включения файла javascript в php-файл на основе вашего условия. код для включения js-файлов не совпадает с файлами php. –

+0

спасибо за помощь! – linuxisthebest33

0

привет в моем случае я использую базовый шаблон модуля, seprated меньшего parts.i имеет 3 основную часть пользовательского интерфейса в моем сайт 1.public site js для всех шаблонов jquery, bootstrap, ..., которые используются во всех шаблонах, должны помещаться здесь 2. стиль или шаблон ja.each имеет папку js, в которой должен быть весь открытый файл js из этих шаблонов 3. каждый модуль в шаблоне имеет js-папку, которая специально для этого модуля должна быть там я делаю это для CSS too.in самом деле, когда я загрузить A Проверьте модуль все это папки,

array_slice(scandir($st_css_style_public_path), 2) 

и создать CSS ссылку или JS скрипт и распечатать окончательную строку адреса в моей странице. , но в некоторых случаях вам нужно вводить мир кода прямо на свою страницу. Я использую папку и файл с именем плагинов-> plugins.php, поместив весь фрагмент скрипта, получим его содержимое и напечатайте его на моей странице.

`$st_plugins .= (file_exists($st_plugin_style_public_path)) ? file_get_contents($st_plugin_style_public_path) : ' '; 

все мой метод визуализации, на мой взгляд это:

public function render($address, $data = '', $cache = 1, $showstyle = 1) { 
     $data['LINKPREFIX'] = '/' . $this->current_holding_unique_name 
       . '/' 
       . $this->current_lang; 
     if (isset($address)) { 
      $path = explode('/', $address); 
      $path[0] = $path[0]; 
      $path[1] = $path[1]; 
     } 
     $template = $this->twig->loadTemplate($path[0] . DS . $path[1] . '.twig'); 
     if ($showstyle) { 
      $css_links = ''; 
      $js_links = ''; 
      $st_plugins = ''; 

      //################################################## 
      //########################## CREATING CSS,JS ADDRESS 
      //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 
      //####### SITE PUBLIC CSS & JS FILES 
      $st_js_public_path = '.' . DS . PUBLIC_DIR . DS . $this->set_address($path[0]) . 'js'; 
      $st_css_public_path = '.' . DS . PUBLIC_DIR . DS . $this->set_address($path[0]) . 'css'; 

      if (file_exists($st_js_public_path) && is_dir($st_js_public_path)) { 
       $ar_public_jsfile_list = array_slice(scandir($st_js_public_path), 2); 
       foreach ($ar_public_jsfile_list as $js_file_name) { 
        $js_links .= $this->create_css_js_link($st_js_public_path . DS . $js_file_name, 'js'); 
       } 
      } 
      if (file_exists($st_css_public_path) && is_dir($st_css_public_path)) { 
       $ar_public_cssfile_list = array_slice(scandir($st_css_public_path), 2); 
       foreach ($ar_public_cssfile_list as $css_file_name) { 
        $css_links .= $this->create_css_js_link($st_css_public_path . DS . $css_file_name, 'css'); 
       } 
      } 

      //####### STYLE PUBLIC CSS & JS & PLUGINS FILES 
      $st_js_style_public_path = '.' . DS . VIEW_DIR . DS . $this->current_style . DS . 'public' . DS . $this->current_direction . DS . 'js'; 
      $st_css_style_public_path = '.' . DS . VIEW_DIR . DS . $this->current_style . DS . 'public' . DS . $this->current_direction . DS . 'css'; 
      $st_plugin_style_public_path = '.' . DS . VIEW_DIR . DS . $this->current_style . DS . 'public' . DS . $this->current_direction . DS . 'plugins' . DS . 'plugins.php'; 
      if (file_exists($st_css_style_public_path) && is_dir($st_css_style_public_path)) { 
       $ar_cssfile_list = array_slice(scandir($st_css_style_public_path), 2); 
       foreach ($ar_cssfile_list as $css_file_name) { 
        $css_links .= $this->create_css_js_link($st_css_style_public_path . DS . $css_file_name, 'css'); 
       } 
      } 
      if (file_exists($st_js_style_public_path) && is_dir($st_js_style_public_path)) { 
       $ar_jsfile_list = array_slice(scandir($st_js_style_public_path), 2); 
       foreach ($ar_jsfile_list as $js_file_name) { 
        $js_links .= $this->create_css_js_link($st_js_style_public_path . DS . $js_file_name, 'js'); 
       } 
      } 
      $st_plugins .= (file_exists($st_plugin_style_public_path)) ? file_get_contents($st_plugin_style_public_path) : ' '; 
      //####### MODULE CSS & JS FILES 
      $st_js_style_path = '.' . DS . VIEW_DIR . DS . $this->current_style . DS . $path[0] . DS . $this->current_direction . DS . 'js'; 
      $st_css_style_path = '.' . DS . VIEW_DIR . DS . $this->current_style . DS . $path[0] . DS . $this->current_direction . DS . 'css'; 
      $st_plugin_path = '.' . DS . VIEW_DIR . DS . $this->current_style . DS . $path[0] . DS . $this->current_direction . DS . 'plugins' . DS . 'plugins.php'; 
      if (file_exists($st_css_style_path) && is_dir($st_css_style_path)) { 
       $ar_cssfile_list = array_slice(scandir($st_css_style_path), 2); 
       foreach ($ar_cssfile_list as $css_file_name) { 
        $css_links .= $this->create_css_js_link($st_css_style_path . DS . $css_file_name, 'css'); 
       } 
      } 
      if (file_exists($st_js_style_path) && is_dir($st_js_style_path)) { 
       $ar_jsfile_list = array_slice(scandir($st_js_style_path), 2); 
       foreach ($ar_jsfile_list as $js_file_name) { 
        $js_links .= $this->create_css_js_link($st_js_style_path . DS . $js_file_name, 'js'); 
       } 
      } 
      $st_plugins .= (file_exists($st_plugin_path) && $showstyle) ? file_get_contents($st_plugin_path) : ' '; 

      //################################################ 
      //################################################ 
      //################################################ 
      //################################################ 
      //@ @ @ CREATING CSS,JS ADDRESS 
      $data['VARCSSADDR'] = $css_links; 
      $data['VARJSADDR'] = $js_links . $st_plugins; 
      $data['VARURL'] = '/'; 
      $data = array_merge($data, lang_translate::$lang); 
      $template->display($data); 
     } else { 
      //$ar_langpropr = language::$ar_lanuage[session::get('current_lang')]; 
      //$data['lang_code'] = $ar_langpropr['lang_code']; 
      $data = array_merge($data, lang_translate::$lang); 
      return $this->twig->render($address . '.twig', $data); 
     } 
    } 

я использую прут двигатель шаблона, так что некоторые не связанные код на свой вопрос здесь, иначе часть для Ajax вызова. заключение: 1-вы можете использовать эту структуру, чтобы добавить или удалить файл из модуля так же просто, как скопировать или удалить файл из его папки. 2- вы можете использовать его для создания правильных JS или CSS, чтобы создать адрес с помощью AJAX и напечатать его в коде

я надеюсь, что это помогло вам и не стесняйтесь как больше вопрос, если вам нужно

+0

Спасибо за помощь! – linuxisthebest33

0

PHP include() являются серверными.

JavaScript является клиентской стороной.

Следовательно, вы не можете использовать include() для JavaScript.

Однако, если вы хотите загрузить JavaScript с URL, который вы хотите, используйте: $url = "JAVASCRIPT URL HERE"; echo('<script src="'. $url .'"></script>');

Смежные вопросы