Jump to content
  • 0

Почему не работает кроссдоменный Ajax в Firefox?


Drix87
 Share

Question

Во всех браузерах кроме Firefox, Ajax работает. Код ниже.

В Firefox выдает следующее:

 

 

Запрос из постороннего источника заблокирован: Политика одного источника запрещает чтение удаленного ресурса наhttps://ХТМЛ.html. Это может быть исправлено путем перемещения ресурса в тот же домен или включением CORS.

 

На сервере откуда берется html, в htaccess прописано:

 

 

Header set Access-Control-Allow-Origin "*"
var urlPage = 'https://страница,где должна происходить магия',           queryLink = 'https://ссылка с айди/?id=',           linkPartners = 'https://ссылка на html на сервере.html';        $.ajax({      url: linkPartners,      success: function(html){             if (urlPage == window.location.href) {            $(".orange-box .blink").html(html).css({              "background": "none",              "padding": "0"            });            $(".orange-box").css('background', 'none');            $(".ob-content").css('background', 'none');        };        $('.table-partners tbody a').attr('href',function(){           linkSub = this.href + $('#inner_link').data('link');           return linkSub;        });      }    });    $.ajax({                url: queryLink + $('#inner_link').data('link'),      success: function(html){                                        if(urlPage == window.location.href ) {          if (html != "") {                        var objJSON = jQuery.parseJSON(html);            if (objJSON != null) {              var balance = objJSON.sum;                   if (balance != null) {                  $('.profileData h4').append('<div class="bal-left">Действительны до <a href="#" target="_blank">1.10.2015</a>: <strong>' + balance + ' </strong></div>');                  return;              }             }          };     }     $('.profileData h4').append('<span style="display:none;"></span>');    }    });
Link to comment
Share on other sites

1 answer to this question

Recommended Posts

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

  • Similar Content

    • By Seadjus
      Добрый день!
      Огромная просьба камнями не кидаться!
      Начал изучать JS , пока нет особых продвижений в изучении.
      помогите оптимизировать игру в пары. по условиям задания необходимо реализовать игру в пары с таймером, выбором количества карт .
      Ниже
      https://codepen.io/Seadjus/pen/VwVedaP
    • By ilya1203
      Прошу помочь с заданием:
      Написать файл скрипта, который генерирует три числа, соответствующие значениям высоты, длины и ширины комнаты. Отобразить в консоли:
      a.Площадь стен комнаты
      b.Объём комнаты
      c.*Объём комнаты за вычетом случайно сгенерированного количества чисел, которые определяет объёмы случайно зашедших в комнату людей.
      (в итоге запустит скрипт последством консоли)
      (заранее огромное спасибо)
    • By Kaido
      Использую готовый плагин для модальных окон(от MaxGraph). Проблема в том, что когда у меня открыто два модальных окна, для примера Форма + Политика конфендициальности, и мне нужно закрыть политику вместе с ней закрывается и другое модальное окно. В JS я не сильно разбираюсь(собственно из за этого и использую готовый плагин), можете помочь кто работал с этим плагином? Я примерно понимаю как он работает, но реализовать чтобы закрывалось только одно не получается.
       
        <div class="content"> <button class="modal-btn" data-path="first" data-animation="fadeInUp" data-speed="1500">Открыть окно 1</button> </div> <div class="modal"> <div class="modal__wrapp" data-target="first"> <div class="modal__content"> <button class="modal__close">Закрыть</button> модальное окно <button data-path="policy">Политика</button> </div> </div> <div class="modal__wrapp" data-target="policy"> <div class="modal__content"> <button class="modal__close">Закрыть</button> политика </div> </div> </div> .modal { --transition-time: 0.3s; position: fixed; left: 0; top: 0; right: 0; bottom: 0; z-index: 1000; cursor: pointer; overflow-y: auto; overflow-x: hidden; text-align: center; opacity: 0; visibility: hidden; transition: opacity var(--transition-time), visibility var(--transition-time); } .modal__wrapp { display: none; cursor: default; width: fit-content; height: fit-content; } .modal__content{ position: absolute; left: 500px; width: 500px; height: 500px; display: flex; color: white; flex-direction: column; text-align: left; background-color: #000; } .modal__content button{ width: 200px; height: 50px; margin: 50px 0; } .modal.is-open { opacity: 1; visibility: visible; transition: opacity var(--transition-time), visibility var(--transition-time); } .modal__wrapp.modal-open { display: flex; } .disable-scroll { position: relative; overflow: hidden; height: 100vh; position: fixed; left: 0; top: 0; width: 100%; } .fade { opacity: 0; transition: opacity var(--transition-time); } .fade.animate-open { opacity: 1; transition: opacity var(--transition-time); } .fadeInUp { opacity: 0; transform: translateY(vw(-100)); transition: opacity var(--transition-time), transform var(--transition-time); } .fadeInUp.animate-open { opacity: 1; transform: translateY(0); transition: opacity var(--transition-time), transform var(--transition-time); } .modal__wrapp[data-target="policy"] .modal__content{ left: 1050px; background-color: #000; opacity: .5; } class Modal { constructor(options) { let defaultOptions = { isOpen: () => {}, isClose: () => {}, } this.options = Object.assign(defaultOptions, options); this.modal = document.querySelector('.modal'); this.speed = false; this.animation = false; this.isOpen = false; this.modalContainer = false; this.previousActiveElement = false; this.fixBlocks = document.querySelectorAll('.fix-block'); this.focusElements = [ 'a[href]', 'input', 'button', 'select', 'textarea', '[tabindex]' ]; this.events(); } events() { if (this.modal) { document.addEventListener('click', function(e){ const clickedElement = e.target.closest('[data-path]'); if (clickedElement) { let target = clickedElement.dataset.path; let animation = clickedElement.dataset.animation; if (clickedElement.classList.contains('modal-close')) { this.close(); } let speed = clickedElement.dataset.speed; this.animation = animation ? animation : 'fade'; this.speed = speed ? parseInt(speed) : 300; this.modalContainer = document.querySelector(`[data-target="${target}"]`); this.open(); return; } if (e.target.closest('.modal__close')) { this.close(); return; } }.bind(this)); window.addEventListener('keydown', function(e) { if (e.keyCode == 27) { if (this.isOpen) { this.close(); } } if (e.keyCode == 9 && this.isOpen) { this.focusCatch(e); return; } }.bind(this)); this.modal.addEventListener('click', function(e) { if (!e.target.classList.contains('modal__wrapp') && !e.target.closest('.modal__wrapp') && this.isOpen) { this.close(); } }.bind(this)); } } open() { this.previousActiveElement = document.activeElement; this.modal.style.setProperty('--transition-time', `${this.speed / 1000}s`); this.modal.classList.add('is-open'); this.disableScroll(); this.modalContainer.classList.add('modal-open'); this.modalContainer.classList.add(this.animation); setTimeout(() => { this.options.isOpen(this); this.modalContainer.classList.add('animate-open'); this.isOpen = true; this.focusTrap(); }, this.speed); } close() { if (this.modalContainer) { this.modalContainer.classList.remove('animate-open'); this.modalContainer.classList.remove(this.animation); this.modal.classList.remove('is-open'); this.modalContainer.classList.remove('modal-open'); this.enableScroll(); this.options.isClose(this); this.isOpen = false; this.focusTrap(); } } focusCatch(e) { const focusable = this.modalContainer.querySelectorAll(this.focusElements); const focusArray = Array.prototype.slice.call(focusable); const focusedIndex = focusArray.indexOf(document.activeElement); if (e.shiftKey && focusedIndex === 0) { focusArray[focusArray.length - 1].focus(); e.preventDefault(); } if (!e.shiftKey && focusedIndex === focusArray.length - 1) { focusArray[0].focus(); e.preventDefault(); } } focusTrap() { const focusable = this.modalContainer.querySelectorAll(this.focusElements); if (this.isOpen) { focusable[0].focus(); } else { this.previousActiveElement.focus(); } } disableScroll() { let pagePosition = window.scrollY; this.lockPadding(); document.body.classList.add('disable-scroll'); document.body.dataset.position = pagePosition; document.body.style.top = -pagePosition + 'px'; } enableScroll() { let pagePosition = parseInt(document.body.dataset.position, 10); this.unlockPadding(); document.body.style.top = 'auto'; document.body.classList.remove('disable-scroll'); window.scroll({ top: pagePosition, left: 0 }); document.body.removeAttribute('data-position'); } lockPadding() { let paddingOffset = window.innerWidth - document.body.offsetWidth + 'px'; this.fixBlocks.forEach((el) => { el.style.paddingRight = paddingOffset; }); document.body.style.paddingRight = paddingOffset; } unlockPadding() { this.fixBlocks.forEach((el) => { el.style.paddingRight = '0px'; }); document.body.style.paddingRight = '0px'; } } const modal = new Modal({ isOpen: (modal) => { console.log(modal); console.log('opened'); }, isClose: () => { console.log('closed'); }, });  
    • By ilyamio
      Здравствуйте. Имеется рабочий скрипт конвертера валют. https://ilyamio.github.io/currencyconverter/
      Мне необходимо изменить источник загрузки курсов на ЦБ РФ вот по этой ссылке: https://www.cbr.ru/scripts/XML_daily.asp
      А также мне необходимо установить ограничение на количество обращений к сайту ЦБ РФ - 1 раз в сутки. При частом обращении, могут заблокировать.
      Вот в этом js файле находятся настройки конвертера:
      const from_currencyEl = document.getElementById('from_currency'); const from_ammountEl = document.getElementById('from_ammount'); const to_currencyEl = document.getElementById('to_currency'); const to_ammountEl = document.getElementById('to_ammount'); const rateEl = document.getElementById('rate'); const exchange = document.getElementById('exchange'); from_currencyEl.addEventListener('change', calculate); from_ammountEl.addEventListener('input', calculate); to_currencyEl.addEventListener('change', calculate); to_ammountEl.addEventListener('input', calculate); exchange.addEventListener('click', () => { const temp = from_currencyEl.value; from_currencyEl.value = to_currencyEl.value; to_currencyEl.value = temp; calculate(); }); function calculate() { const from_currency = from_currencyEl.value; const to_currency = to_currencyEl.value; fetch(`https://api.exchangerate-api.com/v4/latest/${from_currency}`) .then(res => res.json()) .then(res => { const rate = res.rates[to_currency]; rateEl.innerText = `1 ${from_currency} = ${rate} ${to_currency}` to_ammountEl.value = (from_ammountEl.value * rate).toFixed(2); }) } calculate(); Как мне изменить настройки в этом файле чтобы курсы брались с https://www.cbr.ru/scripts/XML_daily.asp и включить ограничение на количество обращений по ссылке cbr.ru - 1 раз в сутки?
      Заранее спасибо всем, кто хотел помочь с решением этой задачи.
    • By vasyl_runner
      $(function () { var mixer = mixitup('.directions__list'); $('.directions__filter-btn').on('click', function () { $('.directions__filter-btn').removeClass('directions__filter-btn--active') $(this).addClass('directions__filter-btn--active') }) })
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue. See more about our Guidelines and Privacy Policy