Table of contentsSpis treści
Table of Contents | ||
---|---|---|
|
...
Korzystanie jQuery and Ajax
...
O jQuery
jQuery is a solid JavaScript library. Among its many advantages:
- Works as expected with numerous web browsers.
- Clear, concise and intuitive architecture.
- Many available plugins.
You can learn more about jQuery on the official websitejest solidną biblioteką JavaScript. Wśród wielu zalet:
- Działa zgodnie z oczekiwaniami wielu przeglądarek internetowych.
- Jasna, zwięzła i intuicyjna architektura
- Wiele dostępnych wtyczek.
Możesz się dowiedzieć więcej o jQuery na oficjalnej stronie: http://jquery.com/
jQuery
...
$
jQuery has the posiada funkcje
function, and the $()
$
namespace, which contains all the other functions.
The $()
function can be used in many ways:
...
nazw, który zawierają wszystkie inne funkcje.
Funkcja $()
może być użyta na wiele sposobów:
- Przy zastosowaniu funkcji jako parametr,
$()
będzie wykonywał funkcje gdy strony w DOM są w pełni załadowane.
Na przykład:$(function(){ /* do something */ });
- When passing a string containing a CSS selector, Po przejściu ciągu zawierającego selektor CSS
$()
will return all the HTML nodes which match the selector.
For instancezwróci wszystkie węzły HTML, które odpowiadają selektorowi.
Na przykład:$('ul#nav');
- That set of nodes can then be assigned to any of jQuery's methods. For instance, if you want to hide the navigation element returned by the above selector.
For instanceTen zestaw węzłów może być przypisany do każdej z metod jQuery. Na przykład. Jeśli chcesz ukryć elementy nawigacji zwracane przez powyższy selektor.
Na przykład:$('ul#nav').slideUp('fast');
When using pure HTML code as its parameter, Przy użyciu czystego kodu HTML jako jego parametru
$()
will create the node (DOM element). That node can, again, be used with any of jQuery's methods.
For instance stworzy węzeł (element DOM). Ten węzeł może znowu być stosowany z dowolną metodą jQuery
Na przykład:$("<li>Sign Off</li>").appendTo("ul#nav");
Note | ||
---|---|---|
W związku z tym te dwie linie są równoważne:
If you are mixing JavaScript libraries in your theme, you might be better off by telling jQuery to free Jeśli mieszasz biblioteki JavaScript w swoim temacie, może będzie lepiej powiedzieć jQuery żeby uwolnić |
You can learn more about Możesz dowiedzieć się więcej na temat jQuery()
and i $()
on the official website na oficjalnej stronie: http://api.jquery.com/jQuery/
...
Funkcje w jQuery
jQuery's $
namespace contains all the functions that are not attached to a specific node.Among these are a few Ajax and utilitarian functions. For instancenamespace $
zawiera wszystkie funkcje, które nie są dołączane do konkretnego węzła.
Wśród nich znajduje się kilka funkcji Ajax I funkcji użytkowych. Na przykład:
Code Block |
---|
$.post('/handler.php', {'action': 'purchase', 'product': 434}, function(data){/* do something */} ); |
You can attach events to a set of nodes returned by Można dołaczyć zdarzenia do zbioru skróconych węzłów zwróconych przez $()
. One of the advantages of using jQuery, once again, is that when handling events, it helps you by harmonizing so that you do not have to cater for each browser specifics.In order to associate a function to a click event, simple add Jedną z zalet korzystania z jQuery, po raz kolejny jest to, że podczas obsługi zdarzenia, pomaga on poprzez harmonizacje, tak, że nie trzeba uzględniać specyfiki każdej przeglądarki.
Aby przypisać funkcje click event, jest prosty dodatek .click(function)
.
In order to generate a W celu wygenerowania click event, you can also use można również użyć .click()
with any parameter. For instance z każdym parametrem. Na przykład: $('#button').click(function(){/* do something */});
You can learn more about Możesz się dowiedzieć więcej na temat jQuery's Ajax and utilitarian functions on the official websitei funkcji użytkowych na oficjalnej stronie:
- http://api.jquery.com/category/ajax/ (for instancena przykład, http://api.jquery.com/jQuery.post/)
- http://api.jquery.com/category/utilities/
Selectors
jQuery offers two ways to select page elements:
...
Selektory
jQuery oferuje dwa spososby, aby wybrać elementy strony:
- Połącz selektory CSS i XPath w ciągu znaków, które są używane z funkcją
$()
. Na przykład:$("div > ul a")
- Using one of the several methods already available in the Użyj jednej z kilku metod, które są już dostępne w
jQuery
namespace.
These two ways can be combined.Oba te spososby mogą być łączone
Code Block |
---|
var my_jQuery_object = $("#my_image"); var my_jQuery_object = $("#menu a"); var my_jQuery_object = $("#id > .classe, #id td:last-child"); /* returns the 'td' elements within the odd 'tr'. */ var my_jQuery_object = $('tr:odd td'); /* returns the fourth paragraph. */ var my_jQuery_object = $("p:eq(4)"); /* returns the 7 first paragraphs. */ var my_jQuery_object = $("p:lt(8)"); |
You can learn more about Możesz dowiedzieć się więcej na temat selektorów jQuery's selectors on the official websitena oficjalnej stronie: http://api.jquery.com/category/selectors/
Methods and callbacks
A whole set of methods are available in the standard API: DOM manipulation, CSS manipulation, event management, visual effects, etc.
For instance, if you wish to have all the paragraphs in a page slowly disappears, use this:
Metody i wywołania zwrotne
Cały zestaw metod dostępny w standardowym API to: manipulacja DOM, manipulacja CSS, event managment, efekty wizualne, etc.
Na przykład jeśli chcesz, aby znikneły powoli wszystkie akapity na stronie, użyj tego:
Code Block |
---|
$("p").fadeOut(); |
Some methods (such as the Niektóre metody (takie jak fadeOut()
one) accept another method as a parameter. Such a method will be executed once the first one is done. That is called a callback.For instance) przyjmują inną metodę jako parametr. Taki sposób wykonany raz jest już zrobiony. To nazywamy wywołaniem zwrotnym
Na przykład:
Code Block |
---|
$(".test").fadeOut("slow",function(){ $(this).fadeIn("slow"); }); |
All of jQuery's methods return a jQuery
object. This makes it possible to chain methods, with no limit. You can even write your code so that it reads just like a function block.
For instance, this code works perfectly well, and is easy to read and to updateWszystkie metody powrotu przedmiotu jQuery
. To sprawia, że metody łańcucha są bez ograniczeń. Można nawet napisać swój kod, tak, że jest on czytany jak blok funkcyjny.
Na przykład, ten kod działa doskonale i łatwy do odczytu i aktualizacji:
Code Block |
---|
$(".emptyContent").append("This is a test") .css("border", "1px solid red") .addClass("fullContent") .removeClass("emptyContent"); |
Available plugins in PrestaShop
Here is a list of the jQuery plugins that are available in a default installation of PrestaShop:
...
Plugin file name
...
Dostępne wtyczki w PrestaShop
To jest lista wtyczek jQuery które są dostępne w domyślnej instalacji PrestaShop:
Nazwa wtyczki | Opis wtyczki |
---|---|
jquery.colorpickerPhotoshop- | style color selectorSelektor stylu kolorów PrestaShop. |
jquery.cookie-plugin | Read, write and delete cookiesOdczytuje, zapisuje i usuwa pliki cookie. |
jquery.dimensionsManage | an element's dimensionsZarządza elementami wymiarów. |
jquery.easingManage | the speed of an animationZarządza prędkością elementów. |
jquery.excanvas | Change the canvas of an element (rounded corners / gradients / opacity / draw line, arc, etc.)Zmienia obszar elementu roboczego (zaokrąglone narożniki/gradienty/krycia/rysowanie lini, łuku itp.). |
jquery.fieldselectionUse and replace the text selected within a zone | Wykorzystuje i zastępuje tekst w wybranej strefie. |
jquery.flip | Flip an Odwraca element. |
jquery.flotCreate | graphs presenting data as curves, bars, etcTworzy wykres prezentacji danych, takich jak krzywe, bary, itp. |
jquery.highlightAdd | syntax colorizationDodaje składnie koloryzacji. |
jquery.hoverIntent | Add a prediction effect on JavaScript's Dodaje efekt przewidywania na JavaScript hover event. |
jquery.idTabs | Manage tabsZarządza kartami. |
jquery.ifxtransferAnimate an element with a transfer from one container to another | Animuje elementem podczas przenoszenia z jednego pojemnika do drugiego. |
jquery.jqminmax | Add Dodaje min-width, max-width, min-height and i max-height on all browsersna wszystkich przeglądarkach. |
jquery.pngFix | Manage transparency in Zarządza przejrzystością w IE 5.5 and i IE 6. |
jquery.scrollToMake the page or element scroll to a certain position | Dodaje strony lub przewijanie elementu do określonej pozycji. |
jquery.serialScrollMake a series of element scroll to a certain position. | Wprowadza szereg.elementów przewijania do określonej pozycji. |
jquery.tabledndDrag and drop a table's rows | Przeciąga i upuszcza wiersze tabeli. |
jquery.typewatchExecute a function when the user has typed some text in a zone and has stopped typing after a certain amount of time | Wykonuje funkcje kiedy użytkownik wpisał jakiś tekst w strefie i przestał pisać po pewnym czasie. |
jquery.validate-creditcard | Validate a credit card number depending on its type. |
...
Weryfikuje numer karty kredytowej w zależności od jego typu. |
Kilka innych narzędzi
jQuery's API is incredibly complete, and you will spend hours finding new possibilities.
Here is a couple of function that can be tremendously useful when creating a theme.
First, each()
, which makes it possible to loop through a list of elementsjest bardzo kompletne, i spędzisz godziny na poszukiwaniu nowych możliwości.
Oto kilka funkcji, które mogą być niezwykle użyteczne podczas tworzenia tematu.
Po pierwsze, each()
, co umożliwia petli przejście przez liste elementów:
Code Block |
---|
$("img").each(function(){ console.log($(this).attr("src")); }); |
SecondPo drugie, browser
, which is an object that helps you know which browser you are working withjest obiektem, który pozwala dowiedzieć się, która przeglądarka pracuje z:
Code Block |
---|
if($.browser.msie) { if($.browser.version == 6) { // Your IE6 specific code. } else { // Code for any other IE browser. } } |
...
Wykonywanie połączeń Ajax
...
z jQuery
...
O Ajax
The term Termin "Ajax" is really an acronym for jest naprawdę skrótem od Asynchronous JavaScript and i XML. It describes the use of JavaScript to load new content into the current page without having to reload the whole page. The process is called asynchronous because once the Ajax request has been sent to the web server, the browser does not have to wait for the answer in order to perform other tasks. The transferred content does not have to be formatted in XML: it can use JSON, HTML or plain text.
In effect, using Ajax makes it possible to build very dynamic websites
You can learn about the Ajax technique on the following sites:
...
Opisuje użycie JavaScript do załadowania nowej zawartości do bieżącej strony bez konieczności przeładowania całęj. Proces ten nazywany jest ansynchronicznym, ponieważ gdy żadanie Ajax zostało wysłane do serwera webowego, przeglądarka nie musi czekać na odpowiedź w celu wykonania innych zadań. Przesyłana treść nie musi być sformatowana w XML, można użyć JSON, HTML, lub zwykły tekst.
W efekcie użycie Ajax sprawia, że mozliwe jest zbudowanie bardzo dynamicznych stron internetowych
Możesz się dowiedzieć więcej na temat techniki Ajax na nastepującej stronie:
- Wikipedia: https://pl.wikipedia.org/wiki/Ajax_%28programming%29AJAX
- Mozilla Developer Network: https://developer.mozilla.org/en/docs/AJAX
Note | ||
---|---|---|
| ||
JavaScript Object Notation is the most used format when transferring data using the Ajax technique, for two main reasons: it is considered lighter than XML, and it can very easily be used by JavaScript, as it resembles a subset of that language. You can learn more about JSON on the following sites :jest najczęściej stosowanym formatem podczas przesyłania danych przy użyciu techniki Ajax, z dwóch głównych powodów, uważa sie, że jest lżejszy niż XML, a to może być bardzo ątwe wykorzystane przez JavaScript gdyż przypomina podzbiór tego języka. Możesz dowiedzieć się więcej o JSON na następujących stronach. |
How to use Ajax in PrestaShop
By default, PrestaShop's controllers use the standard full-page-reload process.
...
Jak użyć Ajax w PrestaShop
Domyśłne kontrolery PrestaShop uzywają standardowej pełnej strony- procesu przeładowania.
Jeśli PrestaShop wykryje parametr "ajax" w GET albo POST zapytania, kontroler ajax
obiektu jest przełączony na true: $this->ajax = true;
.
For instance, if your code triggers a URL like suchNa przykład, Jeśli kod wyzwala URL, takie jak : http://...&ajax&action=updatelist
...the controller will then execute the regulator następnie wykona displayAjaxUpdateList()
method if it exists. If it doesn't exist, it will execute the jeśli metoda istnieje. Jeśli nie istnieje, to wykona displayAjax()
method metodą (by defaultdomyślną).
You therefore have to include the code that will take the Ajax call into account. Here is how you would write a simple Ajax query using Dlatego on musi zawierać kod który weźmie pod uwagę wezwanie Ajax. Oto jak można napisać prostą kwerendę za pomocą Ajax jQuery:
Code Block |
---|
var query = $.ajax({ type: 'POST', url: baseDir + 'modules/mymodule/ajax.php', data: 'method=myMethod&id_data=' + $('#id_data').val(), dataType: 'json', success: function(json) { // .... } }); |
And here is how the Oto jak skrypt ajax.php
script would work będzie działać:
Code Block |
---|
// Located in /modules/mymodule/ajax.php require_once(dirname(__FILE__).'../../../config/config.inc.php'); require_once(dirname(__FILE__).'../../../init.php'); switch (Tools::getValue('method')) { case 'myMethod' : die( Tools::jsonEncode( array('result'=>'my_value')); break; default: exit; } exit; |
As you can see in the code sample above, PrestaShop's Tools
object contains Jak widzisz w przykładzie powyższy kod, PrestaShop Tools
zawiera obiekt jsonEncode()
, a method that makes it easy to turn a PHP array into a JSON objectto metoda, która sprawia, że łatwo przekształcić tablicę PHP do obiektu JSON:
Code Block |
---|
public function displayAjax() { $return = array( 'hasError' => true, 'errors' => 'Ceci est le message' ); die(Tools::jsonEncode($return)); } |
Metody jQuery's
...
Ajax
jQuery.ajax(url [,
...
ustawienia ] )
ParametersParametry:
- url: the URL to which the query should be sent
- settings: options and functions
...
- URL do której należy wysłać zapytanie
- ustwienia: opcje i funkcje
Niektóre opcje:
async
(boolean):
...
domyslną jest true
type
: default is domyślnym jest 'GET'cache
(booleanlogiczna): default is domyślną jest truedata
: GET array sent to the servertablica wysyłana do serweradataType
: either zarównoxml
,json
,script
or albohtml
Some functionsNiektóre funkcje:
beforeSend
: triggered before the Ajax callwyzwalane przed wywołaniem Ajaxerror
: in case of errorw przypadku błędusuccess
: in case of successw przypadku powodzeniatimeout
: in case of timeoutw przypadku przekroczenia czasucomplete
: triggered after the call's success or error, whatever the result
...
- wyzwalane po sukcesie zawołania, bez względu na wynik.
Możesz się dowiedzieć więcej o ajax()
tutaj: http://api.jquery.com/jQuery.ajax/
...
Alternatywny: jQuery.load(url [, data ] [, complete(responseText, textStatus, XMLHttpRequest) ] )
This method is used to directly load the HTML result to an Ajax call, right within an element on the current page.
For instanceMetoda ta stosowana jest do bezpośredniego załadowania wyniku HTML do wywołania Ajax, w obrębie elemenetu na bieżącej stronie.
Na przykład :
Code Block |
---|
$('#result').load('ajax/test.html', function() { alert('Load was performed.'); }); |
...
Alternatywny: jQuery.get( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
This method enables you to call an Ajax script with an HTTP GET query. It is equivalent to the following Ajax call:Metoda ta pozwala na połączenie się z zapytaniem Ajax ze skryptem HTTP GET. Jest to równoznaczne z następującym połączeniem Ajax:
Code Block |
---|
$.ajax({ url: url, data: data, success: success, dataType: dataType }); |
Return values on a jQuery Ajax call
All these jQuery methods return a jqHXR
object, which is an extension of the XMLHTTPRequest
object. That object makes it possible to trigger various functions depending on the result of the call:
...
Wartości zwracane na wywołanie Ajax jQuery
Wszystkie te metody jQuery zwracają obiekt jqHXR,
który jest przedłużeniem obiektu XMLHTTPRequest.
Obiekt ten umożliwia wywołanie różnych funkcji w zależności od wyniku połączenia:
Powodzenie:
jqXHR.done(function(data, textStatus, jqXHR) {});
ErrorBłąd:
jqXHR.fail(function(jqXHR, textStatus, errorThrown) {});
Success or ErrorPowodzenie albo Błąd:
jqXHR.always(function(data|jqXHR, textStatus, jqXHR|errorThrown){ });
Success AND ErrorPowodzenie i Błąd:
jqXHR.then(function(data, textStatus, jqXHR) {}, function(jqXHR, textStatus, errorThrown) {});
Here is an example with functions calls depending on the query's resultOto przykład z połaczenia funkcji w zależności od wyniku kwerendy:
Code Block |
---|
// Assign handlers immediately after making the request, // and remember the jqxhr object for this request var jqxhr = $.get("example.php", function() { alert("success"); }) .done(function() { alert("second success"); }) .fail(function() { alert("error"); }) .always(function() { alert("finished"); }); // perform other work here ... // Set another completion function for the request above jqxhr.always(function(){ alert("second finished"); }); |