Есть ли причина, по которой javascript работает в одной папке и не работает в другой папке на том же веб-сервере?

Добрый день, штабелёры!

Может ли кто-нибудь помочь мне понять, почему простая функция onchange javascript работает в одной папке, но не работает в другой папке на том же веб-сервере (cPanel v120.0.16).

Ссылки ниже перенаправят вас в нерабочую и рабочую папку.

Не рабочая папка

Рабочая папка

Обе папки имеют одинаковые разрешения и тип. Обе папки содержат файл test.php с тем же кодом, что и ниже.

<!DOCTYPE html>
<html>
<body>

<p>Select a new car from the list.</p>

<select id = "mySelect" onchange = "myFunction()">
  <option value = "Audi">Audi</option>
  <option value = "BMW">BMW</option>
  <option value = "Mercedes">Mercedes</option>
  <option value = "Volvo">Volvo</option>
</select>

<p>When you select a new car, a function is triggered which outputs the value of the selected car.</p>

<p id = "demo"></p>

<script>
function myFunction() {
  var x = document.getElementById("mySelect").value;
  document.getElementById("demo").innerHTML = "You selected: " + x;
}
</script>

</body>
</html>


Любые указатели или решения будут иметь огромную помощь. Теплые пожелания

попробуйте переименовать оба файла в html вместо php или опубликуйте воспроизводимый пример, пожалуйста

Stefan Hegny 01.09.2024 14:43
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
3
1
52
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

В консоли рабочего сайта (https://rohigroupofschools.com/presite/test.php ) ошибок не вижу. В консоли нерабочего сайта ( https://rohigroupofschools.com/app/test.php) я вижу десятки сообщений об ошибках типа

Content-Security-Policy: The page’s settings blocked an event handler (script-src-attr) from being executed because it violates the following directive: “default-src 'self'” Source: myFunction() test.php
Content-Security-Policy: The page’s settings blocked an inline script (script-src-elem) from being executed because it violates the following directive: “default-src 'self'” test.php:18:9
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/montserrat/v26/JTUSjIg1_i6t8kCHKm459Wlhyw.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/montserrat/v26/JTUSjIg1_i6t8kCHKm459Wdhyzbi.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/montserrat/v26/JTUSjIg1_i6t8kCHKm459WZhyzbi.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/montserrat/v26/JTUSjIg1_i6t8kCHKm459W1hyzbi.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/montserrat/v26/JTUSjIg1_i6t8kCHKm459WRhyzbi.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/montserrat/v26/JTUSjIg1_i6t8kCHKm459Wlhyw.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/montserrat/v26/JTUSjIg1_i6t8kCHKm459Wdhyzbi.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/montserrat/v26/JTUSjIg1_i6t8kCHKm459WZhyzbi.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/montserrat/v26/JTUSjIg1_i6t8kCHKm459W1hyzbi.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/montserrat/v26/JTUSjIg1_i6t8kCHKm459WRhyzbi.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/montserrat/v26/JTUSjIg1_i6t8kCHKm459Wlhyw.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/montserrat/v26/JTUSjIg1_i6t8kCHKm459Wdhyzbi.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/montserrat/v26/JTUSjIg1_i6t8kCHKm459WZhyzbi.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/montserrat/v26/JTUSjIg1_i6t8kCHKm459W1hyzbi.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/montserrat/v26/JTUSjIg1_i6t8kCHKm459WRhyzbi.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/roboto/v32/KFOlCnqEu92Fr1MmWUlfBBc4.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/roboto/v32/KFOlCnqEu92Fr1MmWUlfChc4EsA.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/roboto/v32/KFOlCnqEu92Fr1MmWUlfCxc4EsA.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/roboto/v32/KFOlCnqEu92Fr1MmWUlfBxc4EsA.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/roboto/v32/KFOlCnqEu92Fr1MmWUlfCBc4EsA.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/roboto/v32/KFOlCnqEu92Fr1MmWUlfABc4EsA.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/roboto/v32/KFOlCnqEu92Fr1MmWUlfCRc4EsA.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/roboto/v32/KFOlCnqEu92Fr1MmEU9fBBc4.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/roboto/v32/KFOlCnqEu92Fr1MmEU9fChc4EsA.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/roboto/v32/KFOlCnqEu92Fr1MmEU9fCxc4EsA.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/roboto/v32/KFOlCnqEu92Fr1MmEU9fBxc4EsA.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/roboto/v32/KFOlCnqEu92Fr1MmEU9fCBc4EsA.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/roboto/v32/KFOlCnqEu92Fr1MmEU9fABc4EsA.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/roboto/v32/KFOlCnqEu92Fr1MmEU9fCRc4EsA.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/roboto/v32/KFOmCnqEu92Fr1Mu4mxK.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/roboto/v32/KFOmCnqEu92Fr1Mu7GxKOzY.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/roboto/v32/KFOmCnqEu92Fr1Mu7WxKOzY.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/roboto/v32/KFOmCnqEu92Fr1Mu4WxKOzY.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/roboto/v32/KFOmCnqEu92Fr1Mu7mxKOzY.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/roboto/v32/KFOmCnqEu92Fr1Mu5mxKOzY.woff2 because it violates the following directive: “default-src 'self'” test.php
Content-Security-Policy: The page’s settings blocked the loading of a resource (font-src) at https://fonts.gstatic.com/s/roboto/v32/KFOmCnqEu92Fr1Mu72xKOzY.woff2 because it violates the following directive: “default-src 'self'” test.php

Настроенные политики безопасности контента (CSP) блокируют выполнение некоторых встроенных скриптов и обработчиков событий, а также загрузку некоторых внешних ресурсов.

Текущий CSP можно найти в заголовке ответа. Нерабочий сайт имеет заголовок

content-security-policy: default-src 'self'; form-action 'self'; object-src 'none'; frame-ancestors 'none'; upgrade-insecure-requests; block-all-mixed-content

На рабочем сайте такого заголовка нет.

Обработчик событий

onchange = "myFunction()"

в

<select id = "mySelect" onchange = "myFunction()">
  <option value = "Audi">Audi</option>
  <option value = "BMW">BMW</option>
  <option value = "Mercedes">Mercedes</option>
  <option value = "Volvo">Volvo</option>
</select>

и элемент сценария

<script>
function myFunction() {
  var x = document.getElementById("mySelect").value;
  document.getElementById("demo").innerHTML = "You selected: " + x;
}
</script>

заблокированы CSP.

Вам необходимо изменить конфигурацию CSP или изменить свой код таким образом, чтобы он учитывал CSP.

script-src-attr self не разрешает встроенные обработчики событий и script-src-elem self не разрешает встроенные скрипты. Один из способов решения проблемы — переместить весь код JavaScript в отдельные файлы одного происхождения и загрузить файлы сценариев.

Также рекомендуется избегать обработчиков событий on..., см. Почему использование onClick() в HTML — плохая практика? и встроенный JavaScript см. Чем встроенный JavaScript плох?. CSP заставляет вас избегать этого.

Большой! Теперь это работает. Спасибо за подсказку по проверке.

user1565795 02.09.2024 06:22

Другие вопросы по теме