Skip to content

Instantly share code, notes, and snippets.

@amorkovin
Last active November 12, 2019 09:42
Show Gist options
  • Save amorkovin/c2d42e00a3953db7430efb7cabcef1e3 to your computer and use it in GitHub Desktop.
Save amorkovin/c2d42e00a3953db7430efb7cabcef1e3 to your computer and use it in GitHub Desktop.
JavaScript и jQuery разное
Все по немногу о JavaScript и Jquery
//jQuery-скрипт в WordPress
jQuery(document).ready(function($) {
});
//ajax, JSON и преобразование объекта, переданного из PHP, в массив
var theme = $('#select-diet-form').data('theme');
var weight = $('#diet-weight option:selected').val();
var weight_ajax = '&weight_ajax=' + weight;
$.ajax({
url: '/wp-content/themes/' + theme + '/ajax-diet.php?select_diet=1' + weight_ajax
}).done(function(result) {
result = JSON.parse(result);
var array = $.map(result, function(value, index) {
return [value];
});
});
В php можно кодировать результат в json так:
echo json_encode($term_in_posts);
$term_in_posts — это ассоциативный массив.
//Необходимые в php-файле строчки для работы в WordPress при работе с ajax
header('Content-Type: text/html; charset=utf-8');
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );
// Обход массива ошибок в JavaScript
for (var i = 0; i < errors.length; i++) {
$('.calc').append('<div class="errors">' + errors[i] + '</div>');
}
//Обход элементов в jQuery
$('#diet-weight option').each(function(indx, element){
$(element).removeAttr('disabled');
});
//Получить данные из Get в JavaScript
var $_GET = {};
document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
function decode(s) {
return decodeURIComponent(s.split("+").join(" "));
}
$_GET[decode(arguments[1])] = decode(arguments[2]);
});
console.log($_GET['term']);
//Отправка данных POST из js в PHP
var data = {'add_block_to_wrap_url': add_block_to_wrap_url, 'add_block_to_wrap_text': add_block_to_wrap_text};
$.ajax({
type: "POST",
url: '/wp-content/plugins/morkovin_abc/ajax-admin.php?add_block=1&wrapid=' + wrapid,
data: {myData:data},
}).done(function(result) {
console.log(result);
});
//Получение данных в php
$obj = $_POST['myData'];
$obj['add_block_to_wrap_url'];
//Сбросить выбор select jQuery
$('#diet-term').prop('selectedIndex', 0);
//Пагинация в WordPress на ajax
//pagination
if ( $('.more-search').length ) {
$('body').on('click', '.more-search:not(.loading)', function() {
var more = $(this);
var container = $(this).prev('.search-result');
var defaultText = more.html();
more.addClass('loading').html( more.data('loading') );
var offset = more.data('offset');
var items = more.data('items');
var theme = more.data('theme');
var search = more.data('search');
$.ajax({
url: $(this).data('theme-url') + '/ajax-pagination.php?search_pagination=1&offset=' + offset + '&items=' + items + '&search=' + search,
}).done(function(html) {
container.append(html);
more.data('offset', offset + items).removeClass('loading').html(defaultText);
if ( $.trim(html) === '' ) {
more.remove();
} else {
if ( $('.last-items').length ) {
more.remove();
}
$('html, body').animate({scrollTop: $('.ajax-first-item:last').offset().top }, 900);
}
});
});
}
//Кнопка «Показать еще» в php
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
if ( $wp_query->max_num_pages > 1 && $paged == 1 ) {
$posts_num = get_option('posts_per_page'); ?>
<div class="more-search"
data-items="<?php echo $posts_num; ?>"
data-offset="<?php echo $posts_num; ?>"
data-search="<?php echo get_search_query(); ?>"
data-theme-url="<?php echo get_template_directory_uri(); ?>"
data-loading="Загрузка..."><span>Больше статей</span>
</div>
<?php
} ?>
//Файл ajax-pagination.php, обратаывающий запрос
<?php
header('Content-Type: text/html; charset=utf-8');
require_once( $_SERVER['DOCUMENT_ROOT'] . '/wp-load.php' );
if ( isset($_GET['search_pagination']) ) $search_pagination = $_GET['search_pagination'];
if ( $search_pagination ) {
$items = $_GET['items'];
$offset = $_GET['offset'];
$search = $_GET['search'];
$args = array(
'post_type' => 'post',
'posts_per_page' => $items,
'offset' => $offset,
's' => $search,
);
$loop = new WP_Query($args);
$last_items = '';
if ( $loop->post_count < $items ) {
$last_items = " last-items";
}
if ($loop->have_posts()) {
$i = 1;
$ajax_first_item = true; //Мне нужна эта переменная в loop-ajax.php, чтобы правильно задать класс первому блоку элементов.
while ($loop->have_posts()) { $loop->the_post();
require 'loop-ajax.php';
$ajax_first_item = false;
}
}
wp_reset_query();
die;
}
die;
// содержимое объейта window
var pathname = window.location.pathname; // Returns path only
var url = window.location.href; // Returns full URL
var origin = window.location.origin; // Returns base URL
window.location.pathname // /account/search
// For reference:
window.location.host // www.somedomain.com (includes port if there is one)
window.location.hostname // www.somedomain.com
window.location.hash // #top
window.location.href // http://www.somedomain.com/account/search?filter=a#top
window.location.port // (empty string)
window.location.protocol // http:
window.location.search // ?filter=a
//Смена url в браузере
https://developer.mozilla.org/ru/docs/Web/API/History/pushState
var state = { 'page_url': url };
var title = url;
window.history.pushState( state, title, url);
//Клик вне элемента для его закрытия
//https://misha.blog/jquery/klik-vne-elementa.html
$(document).mouseup(function (e){
var div = $('.compare-rezults');
if ( !div.is(e.target) && div.has(e.target).length === 0 && !$('.compare-search__field_result-page').is(e.target) ) {
div.fadeOut();
}
});
//Клик по элементу, не имеющему класс
$('body').on('click', '.more:not(.loading)', function() {
});
//Переход по URL
window.location.href = url;
//Доступ к canonical
var canonical_href = $('link[rel="canonical"]').attr('href');
$('link[rel="canonical"]').attr('href', canonical_href);
//Доступ к title
var title_head_page = $(document).find("title").text();
$(document).find("title").text(title_head_page);
//Уникализировать массив
function unique(array){
return array.filter(function(el, index, arr) {
return index == arr.indexOf(el);
});
}
//Сортировка массива
function median(data) {
data.sort((a, b) => a - b);
return data;
}
//Колонки одной высоты
function morkovinSetEqHeight() {
if ( $('.compare__item').length > 1 ) {
var height = [];
$('.compare__item').each(function(indx, element){
$(this).children('div:not(.compare-close)').each(function(j, item){
if (height[j] == undefined ) {
height[j] = [];
}
height[j].push( $(this).height() );
});
});
for (var i = 0; i < height.length; i++) {
height[i] = median( height[i] );
height[i].reverse();
}
$('.compare__item').each(function(indx, element){
$(this).children('div:not(.compare-close)').each(function(j, item){
$(this).css('height', height[j][0] + 'px');
});
});
}
}
//Разделение разрядов
var invest_single = $('.auto-separator');
if ( invest_single.length ) {
var invest_single__text = '';
$.each(invest_single, function() {
invest_single__text = $(this).text();
$(this).text( thousandSeparator(invest_single__text) );
});
}
//Отправка формы на ajax
14
$(function() {
$('form').submit(function(e) {
var $form = $(this);
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize()
}).done(function() {
console.log('success');
}).fail(function() {
console.log('fail');
});
//отмена действия по умолчанию для кнопки submit
e.preventDefault();
});
});
// Проверка наличия свойства у объекта
if ( result.hasOwnProperty('success') ) {
}
// Положить в массив названия свойств объекта
var key_errors = Object.keys(result.error);
//foreaech со свойствами объекта, например
if( key_errors.length ) {
key_errors.forEach(function(item) {
...
}
}
Мигнуть цветом фона
btn.parents('li').css('background-color', 'rgba(255,0,0,0.5)');
setTimeout(() => btn.parents('li').css('background-color', 'transparent'), 100);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment