Ajax как подключить к html
Перейти к содержимому

Ajax как подключить к html

  • автор:

06.Ajax

I’ve sent you each 300 buckeroos. In the form of a tricky Dick fun bill. Knock yourselves out!

Ajax Return Types

  • Everything returned by Ajax is textual data
  • Doesn’t mean it’s plaintext though
    • XML
    • HTML
    • JavaScript
    • JSON
    • Initial usage mostly used XML
      • Server must send Content-Type: text/xml header, XHR will automagically parse the returned data as XML
      • Most of the time a cumbersome work though

      XML Example (1)

      • Data returned

      XML Example (2)

      • JS Implementation
      • Why not let the server prepare a blob of HTML instead of building it after having parse the XML?
        • Data returned
        • JS Implementation

        JavaScript

        • Load in a tad of JavaScript, and then eval() it.
          • Data returned
          • JS Implementation
          • But not always: In this case, it is allowed

          JavaScript: External Files

          • No need for Ajax if you need to include an external file
          • Does give problems though, as you cannot know when the script has finished loading
            • In that case you will need XHR, or — even better — a specific script loader such as RequireJS
            • JSON = JavaScript Object Notation
              • In Short: JSON a JavaScript Object Literal, represented as a string
              • Described by Douglas Crockford in 2006 (RFC 4627)

              JSON Format

              • JSON = One big Object with keys and values
              • Multiple key-value pairs: comma-delimited
              • Keys are of the type string (double quotes required!)
              • Values are string , number , Object , Array , boolean or null

              JSON Example

              • Example
                • XHR doesn’t parse the string to JSON automagically, you will need to manually parse it using JSON.parse() (reverse: JSON.stringify() )
                  • Older browsers that don’t support JSON.parse() require a library to do the parsing.

                  Sidenote: JSON in PHP

                  • Since PHP 5.2, JSON in PHP is really easy
                    • Encode an Array to JSON with json_encode
                    • Decode JSON String into an Object or Associative Array with json_decode
                    • Content-Type: application/json

                    What to choose?

                    • JSON FTW!
                      • Easier to work with (both JS & PHP)
                      • Smaller than XML
                      • Very readable
                      • All modern webapp API’s output JSON

                      Ajax in jQuery

                      Shut up and take my money!

                      • The core function jQuery to make Ajax calls is $.ajax()
                        • Pass in an object to tell jQuery what to call and how

                        $.ajax() Parameters (1)

                        • Five basic parameters
                          • url : A string containing the URL to which the request is sent.
                          • success : A function to be called if the request succeeds.
                          • error : A function to be called if the request fails.
                          • type : Type of request to make ( POST or GET ). Defaults to GET
                          • dataType : Type of data you’re expecting back from the server.
                            • xml
                            • html
                            • script — Will be interpreted automatically. Only via GET .
                            • json — Will be parsed automatically.
                            • jsonp
                            • text
                            • (empty → jQuery will guess the type)

                            $.ajax() Parameters (1)

                            • Other interesting parameters
                              • async : Set to false if you need synchronous requests
                              • data : Extra data to be sent to the server (eg. form data)
                              • headers : Extra headers to be sent along with the request
                              • username & password : HTTP Authentication

                              Sending data

                              • Possible via data parameter
                                • Format is a querystring: key=value&key=value&key=value

                                $.ajax() alternative syntax

                                • jQuery1.5 introduced deferreds which allow this:
                                  • Instead of passsing succes and error functions in the call, you hook them onto the request

                                  Sidenote: Deferreds

                                  • Deferreds are awesome!
                                    • When creating the ajax call, you get back a promise
                                    • The success and error functions are bound to the promise
                                    • When the ajax call is completed, the promise is resolved and the attached functions are executed

                                    Basic Shorthands

                                    • jQuery offers shorthands to make GET and POST requests

                                    Basic Shorthands: $.get()

                                    • Example
                                    • Possible to pass in extra data

                                    Basic Shorthands: $.post()

                                    • Same syntax as $.get()

                                    Specific Shorthands

                                      jQuery also sports other shorthands for commonly used actions

                                        — Load a piece of HTML into an element — Load a piece of JS and run it — Load in a piece of JSON

                                      Specific Shorthands: $.fn.load()

                                      • Example
                                      • Also possible to send extra data and hook a success function (see jQuery API)

                                      Specific Shorthands: $.getScript()

                                      • Example
                                      • Also possible to send extra data and hook a success function (see jQuery API)

                                      Specific Shorthands: $.getJSON()

                                      • Example
                                      • Also possible to send extra data (see jQuery API)

                                      Sidenote: Multiple Calls

                                      • In some cases, you’ll need to do 2 requests before you have all needed data
                                        • Oldskool solution: chain calls
                                          • Invoke call #1
                                          • success function of call #1 will invoke call #2
                                          • success function of call #2 will populate the page

                                          What to use?

                                          • Shorthands allowed, yet if you want to have full control use $.ajax()
                                          • Use deferreds when requiring multiple resources

                                          Ajax Challenges

                                          What’s this? Hermes Conrad is closing the gap. He’s limbo-ed out of retirement and straight into my heart!

                                          Как выводить html с помощью AJAX

                                          Из этой статьи Вы узнаете о том, как можно выводить любой html-код через специальную технологию AJAX . Это не очень легко и требует определенных знаний, но не стоит волноваться, что у вас не получится. Ниже будет дана подробная инструкция, по которой даже новичок сможет разобраться. Прежде чем приступать непосредственно к инструкции, отвечу на вопрос, а вообще зачем это нужно и какие есть варианты.

                                          Вообще есть два способа вывода контента: либо через JavaScript, либо через AJAX. Мое мнение, что лучше использовать AJAX, чем JS, но почему лучше — спросите Вы? Ведь обе технологии прячут текст в отдельных файлах. А ответ в том, что поисковые системы дошли до очень высокого уровня и уже в состоянии определять ссылки, которые содержатся в яваскрипте. Например, Google уже заявил об этом, видимо скоро и Яндекс так же заявит об этом достижении.

                                          Инструкция по выводу контента через AJAX

                                          1. Добавить в заголовочную директорию <head> следующий скрипт:

                                          Это нужно, чтобы подключить необходимые библиотеки для работы AJAX прямо с официального сайта.

                                          2. Создайте html или php документ с кодом, который нужно выводить через AJAX . Например, создадим файл text-dlya-ajax.html и пропишем в нем:

                                          3. Создайте отдельный файл JavaScript (.js). Обычно я его называю ajax.js , чтобы сразу понять его содержимое. Добавьте в него следующий код:

                                          Теперь blockajax будет характеризоваться файлом text-dlya-ajax.html .

                                          Если нужно вывести много таких привязок «блок» = «html-код», то можно прописать сколь угодно много различных соответствий:

                                          4. Подключите файл ajax.js к документу через заголовочный тег <head> :

                                          Важно, чтобы сначала подключалась библиотека jquery.min.js, а уже потом файл ajax.js. Иначе работать не будет. Должно быть так:

                                          5. В месте где нужно вывести html-текст файла text-dlya-ajax.html напишите:

                                          Вместо <div ></div> подгрузиться наш html-код из файла text-dlya-ajax.html . Главная идея: скрывать ненужный код. В итоге кода на странице нету, а вывод нужного нам контента есть.

                                          Больше делать ничего не требуется. Теперь Вы можете легко выводить контент через AJAX .

                                          Вы можете скачать выше описанный пример по следующей ссылке: ajax.rar

                                          Кстати, через AJAX также можно выводить и интерпретировать PHP-код. А это открывает огромные возможности перед Вами.

                                          Зачем нужно выводить html с помощью AJAX (3 причины)
                                          1. Если быть очень кратким, то это нужно для продвижения сайта в поисковых системах. Дело в том, что ссылки внутри сайта как бы передают вес между собой. Те страницы на кого ссылаются чаще, имеют больший вес. Поэтому чтобы более равномерно распределить вес сайта между страницами (а не сливать его весь по сквозным ссылкам) нужно как-то сделать так, чтобы эти сквозные ссылки не учитывались поисковыми машинами.

                                          Например, на многих сайтах можно встретить ссылки на метки, которые стоят на каждой странице сайта в сайдбаре. Получается, что страницы с метками имеют наибольшие веса, хотя не содержат важной информации. Также сюда можно отнести другие лишние ссылки на страницах, которые в принципе не нужны.

                                          Конечно, можно закрыть все ссылки в метках в rel=»nofollow», однако исследования показали, что таким способом теряется вес на сайте, т.е. этот вес никому не передается, он как бы просто испаряется (звучит странно, но это так).

                                          2. Второй причиной использования выводить html через AJAX является уменьшение кода на странице сайта. Опять таки это нужно для поисковых систем. Например, футер сайта постоянно дублирует один и тот же код, который только отнимает лишний вес со страницы, поэтому было бы хорошо этот код убрать, но футер оставить. Аякс идеально подходит для решения этой проблемы.

                                          3. Страница с использованием AJAX грузится поблочно, то есть каждый элемент как бы грузиться синхронно и не зависит от других. Таким образом «тяжелые» элементы на сайте не будут тормозить загрузку других частей сайта. Это более удобно для пользователя, поскольку он видит, что сайт грузится и чувствует себя более спокойно, нежели когда загрузка сайта на чем-то застопорилась.

                                          Getting started

                                          This article guides you through the AJAX basics and gives you some simple hands-on examples to get you started.

                                          What’s AJAX?

                                          AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files. AJAX’s most appealing characteristic is its «asynchronous» nature, which means it can communicate with the server, exchange data, and update the page without having to refresh the page.

                                          The two major features of AJAX allow you to do the following:

                                          • Make requests to the server without reloading the page
                                          • Receive and work with data from the server

                                          Step 1 – How to make an HTTP request

                                          To make an HTTP request to the server with JavaScript, you need an instance of an object with the necessary functionality. This is where XMLHttpRequest comes in.

                                          After making a request, you will receive a response back. At this stage, you need to tell the XMLHttpRequest object which JavaScript function will handle the response, by setting the onreadystatechange property of the object to the function called when the request changes state, like this:

                                          Note that there are no parentheses or parameters after the function name, because you’re assigning a reference to the function, rather than actually calling it. Alternatively, instead of giving a function name, you can use the JavaScript technique of defining functions on the fly (called «anonymous functions») to define the actions that will process the response, like this:

                                          Next, after declaring what happens when you receive the response, you need to actually make the request, by calling the open() and send() methods of the HTTP request object, like this:

                                          • The first parameter of the call to open() is the HTTP request method – GET, POST, HEAD, or another method supported by your server. Keep the method all-capitals as per the HTTP standard, otherwise some browsers (like Firefox) might not process the request. For more information on the possible HTTP request methods, check the specification.
                                          • The second parameter is the URL you’re sending the request to. As a security feature, you cannot call URLs on 3rd-party domains by default. Be sure to use the exact domain name on all of your pages or you will get a «permission denied» error when you call open() . A common pitfall is accessing your site by domain.tld , but attempting to call pages with www.domain.tld . If you really need to send a request to another domain, see HTTP access control (CORS).
                                          • The optional third parameter sets whether the request is asynchronous. If true (the default), JavaScript execution will continue and the user can interact with the page while the server response has yet to arrive. This is the first A in AJAX.

                                          The parameter to the send() method can be any data you want to send to the server if POST -ing the request. Form data should be sent in a format that the server can parse, like a query string:

                                          or other formats, like multipart/form-data , JSON, XML, and so on.

                                          Note that if you want to POST data, you may have to set the MIME type of the request. For example, use the following before calling send() for form data sent as a query string:

                                          Step 2 – Handling the server response

                                          When you sent the request, you provided the name of a JavaScript function to handle the response:

                                          What should this function do? First, the function needs to check the request’s state. If the state has the value of XMLHttpRequest.DONE (corresponding to 4), that means that the full server response was received and it’s OK for you to continue processing it.

                                          The full list of the readyState values is documented at XMLHTTPRequest.readyState and is as follows:

                                          • 0 (uninitialized) or (request not initialized)
                                          • 1 (loading) or (server connection established)
                                          • 2 (loaded) or (request received)
                                          • 3 (interactive) or (processing request)
                                          • 4 (complete) or (request finished and response is ready)

                                          Next, check the HTTP response status codes of the HTTP response. In the following example, we differentiate between a successful and unsuccessful AJAX call by checking for a 200 OK response code.

                                          After checking the state of the request and the HTTP status code of the response, you can do whatever you want with the data the server sent. You have two options to access that data:

                                          • httpRequest.responseText – returns the server response as a string of text
                                          • httpRequest.responseXML – returns the response as an XMLDocument object you can traverse with JavaScript DOM functions

                                          Note that the steps above are valid only if you used an asynchronous request (the third parameter of open() was unspecified or set to true ). If you used a synchronous request you don’t need to specify a function, but this is highly discouraged as it makes for an awful user experience.

                                          Step 3 – A Simple Example

                                          Let’s put it all together with a simple HTTP request. Our JavaScript will request an HTML document, test.html , which contains the text «I’m a test.» Then we’ll alert() the contents of the response. Note that this example uses vanilla JavaScript — no jQuery is involved. Also, the HTML, XML and PHP files should be placed in the same directory.

                                          In this example:

                                          • The user clicks the «Make a request» button;
                                          • The event handler calls the makeRequest() function;
                                          • The request is made and then ( onreadystatechange ) the execution is passed to alertContents() ;
                                          • alertContents() checks if the response was received and OK, then alert() s the contents of the test.html file.

                                          Note: If you do not set header Cache-Control: no-cache the browser will cache the response and never re-submit the request, making debugging challenging. You can also add an always-different GET parameter, like a timestamp or random number (see bypassing the cache)

                                          Note: If the httpRequest variable is used globally, competing functions calling makeRequest() can overwrite each other, causing a race condition. Declaring the httpRequest variable local to a closure containing the AJAX functions avoids this.

                                          In the event of a communication error (such as the server going down), an exception will be thrown in the onreadystatechange method when accessing the response status. To mitigate this problem, you could wrap your if. else statement in a try. catch :

                                          Step 4 – Working with the XML response

                                          In the previous example, after receiving the response to the HTTP request we used the request object’s responseText property, which contained the contents of the test.html file. Now let’s try the responseXML property.

                                          First off, let’s create a valid XML document that we’ll request later on. The document ( test.xml ) contains the following:

                                          Next, in makeRequest() , we need to replace test.html with the XML file we just created:

                                          Then in alertContents() , we need to replace the line alert(httpRequest.responseText); with:

                                          This code takes the XMLDocument object given by responseXML and uses DOM methods to access some of the data contained in the XML document.

                                          Step 5 – Working with data

                                          Finally, let’s send some data to the server and receive a response. Our JavaScript will request a dynamic page this time, test.php , which will take the data we send and return a «computed» string — «Hello, [user data]!» — which we’ll alert().

                                          First we’ll add a text box to our HTML so the user can enter their name:

                                          We’ll also add a line to our event handler to get the user’s data from the text box and send it to the makeRequest() function along with the URL of our server-side script:

                                          We need to modify makeRequest() to accept the user data and pass it along to the server. We’ll change the request method from GET to POST , and include our data as a parameter in the call to httpRequest.send() :

                                          The function alertContents() can be written the same way it was in Step 3 to alert our computed string, if that’s all the server returns. However, let’s say the server is going to return both the computed string and the original user data. So if our user typed «Jane» in the text box, the server’s response would look like this:

                                          To use this data within alertContents() , we can’t just alert the responseText , we have to parse it and alert computedString , the property we want:

                                          The test.php file should contain the following:

                                          For more on DOM methods, be sure to check out Document Object Model (DOM).

                                          Simple timed XHR example

                                          Another simple example follows — here we are loading a text file via XHR, the structure of which is assumed to be like this:

                                          Once the text file is loaded, we split() the items into an array at each newline character ( \n — basically where each line break is in the text file), and then print the complete list of timestamps, and the last timestamp, onto the page.

                                          This is repeated every 5 seconds, using a setInterval() call. The idea would be that a server-side script of some kind would continually update the text file with new timestamps, and our XHR code would be used to report the latest timestamp on the client-side.

                                          jQuery AJAX

                                          The jQuery AJAX features makes it possible and easy use AJAX in your HTML pages. The term AJAX is short for Asynchronous Javascript And XML. AJAX makes it possible to fetch content from a server in the background (asynchronously), and update parts of your page with the new content — all without having to reload the complete HTML page.

                                          The jQuery AJAX features are very advanced, and very comprehensive. I will cover most of jQuery’s AJAX features in this text, but you can lookup the finer detail in jQuery’s AJAX documentation:

                                          jQuery AJAX Example

                                          Here is first a jQuery AJAX example showing how to make an AJAX call in jQuery:

                                          First the $.ajax() function is called. To this function is passed a JavaScript object which contains information about the AJAX call to make. In the example this object contains the URL and data to be sent to the server.

                                          The $.ajax() function returns an object. On this object the example calls three functions: done() , fail() and always() .

                                          The done() function is given a function as parameter. The callback function passed as parameter to the done() function is executed if the AJAX request succeeds. The callback function gets three parameters: data , textStatus and jqXHR . The data parameter is the data returned by the server. The textStatus parameter is the textual status message returned by the server. The jqXHR parameter is the jqXHR object which is also returned by the $.ajax() function.

                                          The fail() is also given a function as parameter. The callback function passed as parameter to the fail() function is called if the AJAX request fails. The callback function gets three parameters: jqXHR , textStatus and errorThrown . The jqXHR parameter is the jqXHR object also returned by the $.ajax() function. The textStatus is the textual status message returned by the server. The errorThrown parameter is the error thrown by jQuery.

                                          The callback function passed to the always() function is called whenever the AJAX request finishes, regardless of whether or not the AJAX request succeeds or fails. The three parameters passed to the callback function will be either the same three parameters passed to done() or fail() , depending on whether the AJAX request succeeds or fails.

                                          jQuery AJAX Before Version 1.8.0

                                          Before version 1.8.0 of jQuery the object returned from the jQuery $.ajax() function did not contain the done() , fail() and always() functions. Instead, these functions were called success() , error() and complete() .

                                          jQuery AJAX After Version 1.8.0

                                          From jQuery 1.8.0 the $.ajax() function returns a jqXHR object which implements the promise interface ( done() , fail() , always() etc.) instead of of the success() , error() and complete() functions. The success() , error() and complete() functions are now deprecated. The promise interface is described in my text about jQuery deferred objects.

                                          Receiving HTML With AJAX

                                          By default jQuery AJAX function does not parse the data received from the server. You can insert it raw into a div , like this:

                                          Notice how the done() function selects a div with the id theDiv , and calls its html() function, passing as parameter the data received from the server.

                                          Receiving JSON With AJAX

                                          If you want jQuery to interpret the data received from the server as JSON, you must add the dataType : ‘json’ field to the JavaScript object passed as parameter to the $.ajax() call. Imagine you get a JSON object back from the server that looks like this:

                                          Then you can parse that JSON object, and reference the param1 property, with this $.ajax() call:

                                          Sending Parameters in The AJAX Request

                                          You can send parameters to the server via jQuery’s AJAX functions. You have already seen examples of that. It’s the data property of the JavaScript object passed to the $.ajax() function which contain the data to send to the server. Here is an example with the data object marked in bold:

                                          The data property should always be a JavaScript object. It’s properties are serialized into a reqular query string (for GET requests), or a normal post body parameter string (for POST requests). This serialized string is then sent to the server, along with the AJAX request.

                                          On the server you can read the properties of the data object as if they were sent as simple request parameters, via either GET or POST. Just like if the properties had been fields in a form. In the example above, the server would be able to read two request properties: name and desc .

                                          Sending Raw Data in The AJAX Request

                                          If you do not want jQuery to convert the data object into a serialized parameter string, you can avoid this by setting the processData : false in the JavaScript object passed to the $.ajax() function. Here is an example:

                                          Notice the processData property which is set to false . This tells jQuery not to process the data property before sending it to the server.

                                          Second, notice the type property, which is set to «POST» . This tells jQuery to POST the data to the server.

                                          Third, notice how the data property is now just a string of raw data to be sent to the server. You cannot use a JavaScript object as data property, when you do not process the data before sending them.

                                          Sending JSON in The AJAX Request

                                          If you need to send a JavaScript object as a JSON string to the server with an AJAX request, you need to convert the JavaScript object to a JSON string and send the string as raw data. Here is a jQuery JSON post example:

                                          HTTP GET and POST

                                          HTTP requests can be send as either, GET, POST, PUT, DELETE or HEAD requests. Here I will show you how to do a GET and POST request. Since AJAX requests are HTTP requests, you can also specify which HTTP method to use with your jQuery AJAX requests.

                                          As you have seen earlier, the HTTP method to use can be passed to the $.ajax() via its JavaScript parameter object. You do so by setting the type parameter of the parameter object. Here is first a HTTP GET example using jQuery’s AJAX function:

                                          And here is a HTTP POST example using jQuery’s AJAX function:

                                          The $.get() and $.post() Functions

                                          jQuery has two functions that can be used to send simplified HTTP GET and HTTP POST requests. These functions are the $.get() and $.post() functions.

                                          Here is an example showing how to use jQuery’s $.get() function:

                                          The $.get() function takes a URL and a request parameter object as parameters. The $.get() function returns a jqXHR object just like the $.ajax() function. The handling of the response is thus similar to how you handle the response with the $.ajax() function.

                                          jQuery’s $.post() function works in the same way. Here is an example:

                                          The $.getJSON() Function

                                          The $.get() and $.post() functions do not process the data returned by the server. If you want the data returned by the server interpreted as JSON, you can use jQuery’s $.getJSON() function: Here is a $.getJSON() example:

                                          As you can see, the $.getJSON() function works much like the $.get() and $.post() functions. The only difference is that the data parameter passed to the callback function set via done() is now a JavaScript object.

                                          The load() Function

                                          jQuery also has a function called load() which can be called on a selected element. The load() element loads some HTML via AJAX and inserts it into the selected element. Here is a jQuery load() example:

                                          And with request parameters:

                                          And with a callback that is called when load() finishes:

                                          You can also insert just a part of the HTML loaded. If you append a space + jQuery selector string after the url then load() will only inserted the part of the loaded HTML matching the selector. Here is an example:

                                          This example loads the html-fragment.jsp HTML fragment, selects the element with the id div2 from that fragment and inserts only that element, regardless of what more the HTML fragment contains.

                                          Note: If the loaded HTML contains any JavaScript it will get executed when the HTML is inserted into the target HTML element. However, if you load a fragment (URL + jQuery selector) then any JavaScript found in the loaded file is remove before the HTML is inserted. In general, don’t use load() to load JavaScript (unless you absolutely need to load HTML and JavaScript together). jQuery has the $.getScript() function for that purpose.

                                          The $.getScript() Function

                                          The $.getScript() function in jQuery loads a JavaScript file and executes it. This function uses jQuery’s underlying AJAX functions so the $.getScript() function cannot load scripts from other domains than the HTML page making the request was loaded from (just like with ordinary AJAX calls).

                                          Here is a jQuery $.getScript() example:

                                          A jQuery $.getScript() with parameters example:

                                          And a jQuery $.getScript() with callback example:

                                          The last function call would also work with the parameters object omitted.

                                          Global AJAX Functions

                                          jQuery has a set of global AJAX functions which you can use to listen for AJAX events across all AJAX requests sent via jQuery. These global AJAX functions are:

                                          • .ajaxSend()
                                          • .ajaxStart()
                                          • .ajaxStop()
                                          • .ajaxSuccess()
                                          • .ajaxError()
                                          • .ajaxComplete()

                                          The callback function registered with the ajaxSend() function is called before every AJAX request is sent. Here is an example:

                                          Notice that the ajaxSend() is called on a jQuery selection object.

                                          The callback function registered with the ajaxStart() function is called before an AJAX request is sent, if there are no currently executing AJAX requests. Here is an example:

                                          The callback function registered with the ajaxStop() function is called after an AJAX request finishes, if there are no other executing AJAX requests. Here is an example:

                                          The callback function registered with the ajaxSuccess() function is called whenever an AJAX request succeeds. Here is an example:

                                          The callback function registered with the ajaxError() function is called whenever an AJAX request fails. Here is an example:

                                          The callback function registered with the ajaxComplete() function is called whenever an AJAX request completes, regardless of whether the AJAX request succeeds or fails. Here is an example:

                                          The jqXHR Object

                                          The jqXHR object returned by many of jQuery’s AJAX functions contains some useful information. Note, that some of this information is not available until the web server has sent back a response, meaning it is available from inside the done() , fail() or always() callback functions.

                                          The jqXHR object contains these properties and functions:

                                          • status
                                          • statusText
                                          • responseText
                                          • responseXML
                                          • getAllResponseHeaders()
                                          • getResponseHeader()
                                          • abort()

                                          The status property contains the HTTP status code (e.g. 200 or 404 etc.) sent back by the web server.

                                          The statusText property contains the text success or error depending on whether the AJAX request succeeded or failed.

                                          The responseText contains the body of the HTTP response sent back by the server, if the response is sent as text (e.g. content type text/html , text/plain or application/json ).

                                          The responseXML property contains the body of the HTTP response sent back by the server, if the response is sent back as XML (e.g. content type text/xml or application/xml ).

                                          The getAllResponseHeaders() return the HTTP response headers as a string. Each header is listed on its own line with a header name, colon and header value. For instance:

                                          The getResponseHeader() function can be used to access individual HTTP response headers. You pass the name of the HTTP header like this:

                                          The abort() function on the jqXHR object can be used to abort the AJAX (HTTP) request before it finishes. You should call this function before any of the done() , fail() or always() callback functions are called. These callback functions are called when the server has sent back a response, and at that time it is too late to abort the AJAX call.

                                          Handling Errors

                                          If an AJAX request fails, you can react to the failure inside the callback function added via the fail() function of the object returned by the $.ajax() function. Here is a jQuery AJAX error handling example:

                                          The callback function passed to the done() function will get executed if an error occurs in the AJAX request above. Inside this callback function you can handle the error. Handling the error will normally consist of notifying the user that the request failed. This example displays an alert, but you could also insert the error message into an HTML element somewhere in the page.

                                          Remember, you have access to the HTTP status code returned with response from the server. In some cases you may need to react differently depending on the value of this code. Here is a simple example:

                                          You may also look at the response headers or the response body. Here is an example of that:

                                          ajaxError()

                                          Often, you will handle all AJAX errors in the same way. Instead of having to set fail() handlers on every single AJAX call, you can use the global function ajaxError() to handle a single AJAX error callback function. Here is a jQuery ajaxError() example:

                                          Notice how no fail() handler is attached to the AJAX request. AJAX error handling for all AJAX requests is now handled by the callback function passed to $(document).ajaxError() . You have access to the jqXHR object in this callback too, as well as the AJAX options object that produced the request that failed etc.

                                          $.ajaxSetup()

                                          The $.ajaxSetup() function can be used to set options to be used for all AJAX calls, including those performed via $.ajax() , load() , $.get() etc. The options you can set are the same options as you can pass to a $.ajax() call. For instance, this example sets the type property of all AJAX calls to POST :

                                          Now all AJAX calls will be HTTP POST requests unless a request explicitly overrides that property. An AJAX request can override that like this:

                                          By explicitly setting the type property in the AJAX options object, the $.ajax() call overrides the global settings setup via $.ajaxSetup()

                                          The jQuery documentation recommends that you use $.ajaxSetup() with care. Setting global options can lead to unforeseen side effects (AJAX request being fired with the wrong options).

                                          $.ajaxPrefilter()

                                          The $.ajaxPrefilter() function in jQuery is used to set a pre-filtering function that can filter all AJAX calls before they are sent. By filtering is meant that the AJAX options object passed to the $.ajax() function can be changed («filtered») before the request is sent.

                                          Here is a jQuery AJAX $.ajaxPrefilter() example:

                                          This example sets a prefilter function which checks if the options object’s url property contains the substring «/app». If it does, the options.type is set to POST .

                                          The options parameter passed to the filter function is the options object which is about to be processed by the $.ajax() function. This object contains a merge of the settings set via $.ajaxSetup() and the options object passed to the $.ajax() function when it was called.

                                          The originalOptions object contains the options object that was passed to the $.ajax() function without any options merged in from the options set via $.ajaxSetup() .

                                          The jqXHR object is the normal jqXHR object which will be used to execute this AJAX request.

                                          The main difference between the $.ajaxSetup() function and $.ajaxPrefilter() function is, that the $.ajaxSetup() function takes a static options object as parameter. These options will be applied to all AJAX requests. The $.ajaxPrefilter() takes a function as parameter. A function can perform more intelligent filtering of the options than a simple merge of default options with request options.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *