Jquery get fail error

Description: Load data from the server using a HTTP GET request.

jQuery.get( url [, data ] [, success ] [, dataType ] )Returns: jqXHR

Description: Load data from the server using a HTTP GET request.

  • version added: 1.0jQuery.get( url [, data ] [, success ] [, dataType ] )

    • url

      A string containing the URL to which the request is sent.

    • data

      A plain object or string that is sent to the server with the request.

    • success

      A callback function that is executed if the request succeeds. Required if dataType is provided, but you can use null or jQuery.noop as a placeholder.

    • dataType

      The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).

  • version added: 1.12-and-2.2jQuery.get( [settings ] )

    • settings

      A set of key/value pairs that configure the Ajax request. All properties except for url are optional. A default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) for a complete list of all settings. The type option will automatically be set to GET.

This is a shorthand Ajax function, which is equivalent to:

The success callback function is passed the returned data, which will be an XML root element, text string, JavaScript file, or JSON object, depending on the MIME type of the response. It is also passed the text status of the response.

As of jQuery 1.5, the success callback function is also passed a «jqXHR» object (in jQuery 1.4, it was passed the XMLHttpRequest object). However, since JSONP and cross-domain GET requests do not use XHR, in those cases the jqXHR and textStatus parameters passed to the success callback are undefined.

Most implementations will specify a success handler:

1

2

3

4

$.get( "ajax/test.html", function( data ) {

$( ".result" ).html( data );

alert( "Load was performed." );

This example fetches the requested HTML snippet and inserts it on the page.

The jqXHR Object

As of jQuery 1.5, all of jQuery’s Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or «jqXHR,» returned by $.get() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information). The jqXHR.done() (for success), jqXHR.fail() (for error), and jqXHR.always() (for completion, whether success or error; added in jQuery 1.6) methods take a function argument that is called when the request terminates. For information about the arguments this function receives, see the jqXHR Object section of the $.ajax() documentation.

The Promise interface also allows jQuery’s Ajax methods, including $.get(), to chain multiple .done(), .fail(), and .always() callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

// Assign handlers immediately after making the request,

// and remember the jqxhr object for this request

var jqxhr = $.get( "example.php", function() {

alert( "second success" );

// Perform other work here ...

// Set another completion function for the request above

jqxhr.always(function() {

alert( "second finished" );

Deprecation Notice

The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callback methods are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

Additional Notes:

  • Due to browser security restrictions, most «Ajax» requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, port, or protocol.
  • If a request with jQuery.get() returns an error code, it will fail silently unless the script has also called the global .ajaxError() method. Alternatively, as of jQuery 1.5, the .error() method of the jqXHR object returned by jQuery.get() is also available for error handling.
  • Script and JSONP requests are not subject to the same origin policy restrictions.

Examples:

Request the test.php page, but ignore the return results.

Request the test.php page and send some additional data along (while still ignoring the return results).

1

$.get( "test.php", { name: "John", time: "2pm" } );

Pass arrays of data to the server (while still ignoring the return results).

1

$.get( "test.php", { "choices[]": ["Jon", "Susan"] } );

Alert the results from requesting test.php (HTML or XML, depending on what was returned).

1

2

3

$.get( "test.php", function( data ) {

alert( "Data Loaded: " + data );

Alert the results from requesting test.cgi with an additional payload of data (HTML or XML, depending on what was returned).

1

2

3

4

$.get( "test.cgi", { name: "John", time: "2pm" } )

alert( "Data Loaded: " + data );

Get the test.php page contents, which has been returned in json format (<?php echo json_encode( array( «name»=>»John»,»time»=>»2pm» ) ); ?>), and add it to the page.

1

2

3

4

5

$.get( "test.php", function( data ) {

.append( "Name: " + data.name ) // John

.append( "Time: " + data.time ); // 2pm

Get another page on the same domain. Outputs to console both the data returned and the type of data returned.

1

2

3

4

5

6

// If this was sent on https://api.jquery.com/jQuery.get/ you will

// get the response result of https://api.jquery.com/jQuery.ajax/

$.get( "/jQuery.ajax/", function( data ) {

console.log( typeof data ); // string

console.log( data ); // HTML content of the jQuery.ajax page

Содержание

  1. jQuery.get()
  2. jQuery.get( url [, data ] [, success ] [, dataType ] ) Returns: jqXHR
  3. version added: 1.0 jQuery.get( url [, data ] [, success ] [, dataType ] )
  4. version added: 1.12-and-2.2 jQuery.get( [settings ] )
  5. The jqXHR Object
  6. jQuery.get()
  7. jQuery.get( url [, data ] [, success ] [, dataType ] ) Returns: jqXHR
  8. version added: 1.0 jQuery.get( url [, data ] [, success ] [, dataType ] )
  9. version added: 1.12-and-2.2 jQuery.get( [settings ] )
  10. The jqXHR Object
  11. jQuery.ajax()
  12. jQuery.ajax( url [, settings ] ) Returns: jqXHR
  13. version added: 1.5 jQuery.ajax( url [, settings ] )
  14. version added: 1.0 jQuery.ajax( [settings ] )
  15. The jqXHR Object
  16. Callback Function Queues
  17. Data Types
  18. Sending Data to the Server
  19. Advanced Options

jQuery.get()

jQuery.get( url [, data ] [, success ] [, dataType ] ) Returns: jqXHR

Description: Load data from the server using a HTTP GET request.

version added: 1.0 jQuery.get( url [, data ] [, success ] [, dataType ] )

version added: 1.12-and-2.2 jQuery.get( [settings ] )

This is a shorthand Ajax function, which is equivalent to:

The success callback function is passed the returned data, which will be an XML root element, text string, JavaScript file, or JSON object, depending on the MIME type of the response. It is also passed the text status of the response.

As of jQuery 1.5, the success callback function is also passed a «jqXHR» object (in jQuery 1.4, it was passed the XMLHttpRequest object). However, since JSONP and cross-domain GET requests do not use XHR , in those cases the jqXHR and textStatus parameters passed to the success callback are undefined.

Most implementations will specify a success handler:

This example fetches the requested HTML snippet and inserts it on the page.

The jqXHR Object

As of jQuery 1.5, all of jQuery’s Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or «jqXHR,» returned by $.get() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information). The jqXHR.done() (for success), jqXHR.fail() (for error), and jqXHR.always() (for completion, whether success or error; added in jQuery 1.6) methods take a function argument that is called when the request terminates. For information about the arguments this function receives, see the jqXHR Object section of the $.ajax() documentation.

The Promise interface also allows jQuery’s Ajax methods, including $.get() , to chain multiple .done() , .fail() , and .always() callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.

Источник

jQuery.get()

jQuery.get( url [, data ] [, success ] [, dataType ] ) Returns: jqXHR

Description: Load data from the server using a HTTP GET request.

version added: 1.0 jQuery.get( url [, data ] [, success ] [, dataType ] )

version added: 1.12-and-2.2 jQuery.get( [settings ] )

This is a shorthand Ajax function, which is equivalent to:

The success callback function is passed the returned data, which will be an XML root element, text string, JavaScript file, or JSON object, depending on the MIME type of the response. It is also passed the text status of the response.

As of jQuery 1.5, the success callback function is also passed a «jqXHR» object (in jQuery 1.4, it was passed the XMLHttpRequest object). However, since JSONP and cross-domain GET requests do not use XHR , in those cases the jqXHR and textStatus parameters passed to the success callback are undefined.

Most implementations will specify a success handler:

This example fetches the requested HTML snippet and inserts it on the page.

The jqXHR Object

As of jQuery 1.5, all of jQuery’s Ajax methods return a superset of the XMLHTTPRequest object. This jQuery XHR object, or «jqXHR,» returned by $.get() implements the Promise interface, giving it all the properties, methods, and behavior of a Promise (see Deferred object for more information). The jqXHR.done() (for success), jqXHR.fail() (for error), and jqXHR.always() (for completion, whether success or error; added in jQuery 1.6) methods take a function argument that is called when the request terminates. For information about the arguments this function receives, see the jqXHR Object section of the $.ajax() documentation.

The Promise interface also allows jQuery’s Ajax methods, including $.get() , to chain multiple .done() , .fail() , and .always() callbacks on a single request, and even to assign these callbacks after the request may have completed. If the request is already complete, the callback is fired immediately.

Источник

jQuery.ajax()

jQuery.ajax( url [, settings ] ) Returns: jqXHR

Description: Perform an asynchronous HTTP (Ajax) request.

version added: 1.5 jQuery.ajax( url [, settings ] )

version added: 1.0 jQuery.ajax( [settings ] )

Data to be sent to the server. If the HTTP method is one that cannot have an entity body, such as GET, the data is appended to the URL.

When data is an object, jQuery generates the data string from the object’s key/value pairs unless the processData option is set to false . For example, < a: «bc», d: «e,f» >is converted to the string «a=bc&d=e%2Cf» . If the value is an array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). For example, < a: [1,2] >becomes the string «a%5B%5D=1&a%5B%5D=2» with the default traditional: false setting.

When data is passed as a string it should already be encoded using the correct encoding for contentType , which by default is application/x-www-form-urlencoded .

In requests with dataType: «json» or dataType: «jsonp» , if the string contains a double question mark ( ?? ) anywhere in the URL or a single question mark ( ? ) in the query string, it is replaced with a value generated by jQuery that is unique for each copy of the library on the page (e.g. jQuery21406515378922229067_1479880736745 ).

An object of numeric HTTP codes and functions to be called when the response has the corresponding code. For example, the following will alert when the response status is a 404:

If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error (including 3xx redirect), they take the same parameters as the error callback.

In jQuery 1.5, the withCredentials property was not propagated to the native XHR and thus CORS requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ should you require the use of it.

The $.ajax() function underlies all Ajax requests sent by jQuery. It is often unnecessary to directly call this function, as several higher-level alternatives like $.get() and .load() are available and are easier to use. If less common options are required, though, $.ajax() can be used more flexibly.

At its simplest, the $.ajax() function can be called with no arguments:

Note: Default settings can be set globally by using the $.ajaxSetup() function.

This example, using no options, loads the contents of the current page, but does nothing with the result. To use the result, you can implement one of the callback functions.

The jqXHR Object

The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser’s native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader() method. When the transport mechanism is something other than XMLHttpRequest (for example, a script tag for a JSONP request) the jqXHR object simulates native XHR functionality where possible.

As of jQuery 1.5.1, the jqXHR object also contains the overrideMimeType() method (it was available in jQuery 1.4.x, as well, but was temporarily removed in jQuery 1.5). The .overrideMimeType() method may be used in the beforeSend() callback function, for example, to modify the response content-type header:

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax() request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include:

    jqXHR.done(function( data, textStatus, jqXHR ) <>);

An alternative construct to the success callback option, refer to deferred.done() for implementation details.

jqXHR.fail(function( jqXHR, textStatus, errorThrown ) <>);

An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.

jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) < >); (added in jQuery 1.6)

An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.

In response to a successful request, the function’s arguments are the same as those of .done() : data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail() : the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.

jqXHR.then(function( data, textStatus, jqXHR ) <>, function( jqXHR, textStatus, errorThrown ) <>);

Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.

Deprecation Notice: The jqXHR.success() , jqXHR.error() , and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done() , jqXHR.fail() , and jqXHR.always() instead.

The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.

For backward compatibility with XMLHttpRequest , a jqXHR object will expose the following properties and methods:

  • readyState
  • responseXML and/or responseText when the underlying request responded with xml and/or text, respectively
  • status
  • statusText (may be an empty string in HTTP/2)
  • abort( [ statusText ] )
  • getAllResponseHeaders() as a string
  • getResponseHeader( name )
  • overrideMimeType( mimeType )
  • setRequestHeader( name, value ) which departs from the standard by replacing the old value with the new one rather than concatenating the new value to the old one
  • statusCode( callbacksByStatusCode )

No onreadystatechange mechanism is provided, however, since done , fail , always , and statusCode cover all conceivable requirements.

Callback Function Queues

The beforeSend , error , dataFilter , success and complete options all accept callback functions that are invoked at the appropriate times.

As of jQuery 1.5, the fail and done , and, as of jQuery 1.6, always callback hooks are first-in, first-out managed queues, allowing for more than one callback for each hook. See Deferred object methods, which are implemented internally for these $.ajax() callback hooks.

The callback hooks provided by $.ajax() are as follows:

  1. beforeSend callback option is invoked; it receives the jqXHR object and the settings object as parameters.
  2. error callback option is invoked, if the request fails. It receives the jqXHR , a string indicating the error type, and an exception object if applicable. Some built-in errors will provide a string as the exception object: «abort», «timeout», «No Transport».
  3. dataFilter callback option is invoked immediately upon successful receipt of response data. It receives the returned data and the value of dataType , and must return the (possibly altered) data to pass on to success .
  4. success callback option is invoked, if the request succeeds. It receives the returned data, a string containing the success code, and the jqXHR object.
  5. Promise callbacks — .done() , .fail() , .always() , and .then() — are invoked, in the order they are registered.
  6. complete callback option fires, when the request finishes, whether in failure or success. It receives the jqXHR object, as well as a string containing the success or error code.

Data Types

Different types of response to $.ajax() call are subjected to different kinds of pre-processing before being passed to the success handler. The type of pre-processing depends by default upon the Content-Type of the response, but can be set explicitly using the dataType option. If the dataType option is provided, the Content-Type header of the response will be disregarded.

The available data types are text , html , xml , json , jsonp , and script .

If text or html is specified, no pre-processing occurs. The data is simply passed on to the success handler, and made available through the responseText property of the jqXHR object.

If xml is specified, the response is parsed using jQuery.parseXML before being passed, as an XMLDocument , to the success handler. The XML document is made available through the responseXML property of the jqXHR object.

If json is specified, the response is parsed using jQuery.parseJSON before being passed, as an object, to the success handler. The parsed JSON object is made available through the responseJSON property of the jqXHR object.

If script is specified, $.ajax() will execute the JavaScript that is received from the server before passing it on to the success handler as a string.

If jsonp is specified, $.ajax() will automatically append a query string parameter of (by default) callback=? to the URL. The jsonp and jsonpCallback properties of the settings passed to $.ajax() can be used to specify, respectively, the name of the query string parameter and the name of the JSONP callback function. The server should return valid JavaScript that passes the JSON response into the callback function. $.ajax() will execute the returned JavaScript, calling the JSONP callback function, before passing the JSON object contained in the response to the $.ajax() success handler.

For more information on JSONP, see the original post detailing its use.

Sending Data to the Server

By default, Ajax requests are sent using the GET HTTP method. If the POST method is required, the method can be specified by setting a value for the type option. This option affects how the contents of the data option are sent to the server. POST data will always be transmitted to the server using UTF-8 charset, per the W3C XMLHTTPRequest standard.

Advanced Options

The global option prevents handlers registered using .ajaxSend() , .ajaxError() , and similar methods from firing when this request would trigger them. This can be useful to, for example, suppress a loading indicator that was implemented with .ajaxSend() if the requests are frequent and brief. With cross-domain script and JSONP requests, the global option is automatically set to false . See the descriptions of these methods below for more details.

If the server performs HTTP authentication before providing a response, the user name and password pair can be sent via the username and password options.

Ajax requests are time-limited, so errors can be caught and handled to provide a better user experience. Request timeouts are usually either left at their default or set as a global default using $.ajaxSetup() rather than being overridden for specific requests with the timeout option.

By default, requests are always issued, but the browser may serve results out of its cache. To disallow use of the cached results, set cache to false . To cause the request to report failure if the asset has not been modified since the last request, set ifModified to true .

The scriptCharset allows the character set to be explicitly specified for requests that use a

Источник

This is a tutorial on how to handle errors when making Ajax requests via the jQuery library. A lot of developers seem to assume that their Ajax requests will always succeed. However, in certain cases, the request may fail and you will need to inform the user.

Here is some sample JavaScript code where I use the jQuery library to send an Ajax request to a PHP script that does not exist:

$.ajax({
     url: 'does-not-exist.php',
     success: function(returnData){
         var res = JSON.parse(returnData);
     },
     error: function(xhr, status, error){
         var errorMessage = xhr.status + ': ' + xhr.statusText
         alert('Error - ' + errorMessage);
     }
});

If you look at the code above, you will notice that I have two functions:

  • success: The success function is called if the Ajax request is completed successfully. i.e. If the server returns a HTTP status of 200 OK. If our request fails because the server responded with an error, then the success function will not be executed.
  • error: The error function is executed if the server responds with a HTTP error. In the example above, I am sending an Ajax request to a script that I know does not exist. If I run the code above, the error function will be executed and a JavaScript alert message will pop up and display information about the error.

The Ajax error function has three parameters:

  • jqXHR
  • textStatus
  • errorThrown

In truth, the jqXHR object will give you all of the information that you need to know about the error that just occurred. This object will contain two important properties:

  • status: This is the HTTP status code that the server returned. If you run the code above, you will see that this is 404. If an Internal Server Error occurs, then the status property will be 500.
  • statusText: If the Ajax request fails, then this property will contain a textual representation of the error that just occurred. If the server encounters an error, then this will contain the text “Internal Server Error”.

Obviously, in most cases, you will not want to use an ugly JavaScript alert message. Instead, you would create an error message and display it above the Ajax form that the user is trying to submit.

JQuery 3.0: The error, success and complete callbacks are deprecated.

Update: As of JQuery 3.0, the success, error and complete callbacks have all been removed. As a result, you will have to use the done, fail and always callbacks instead.

An example of done and fail being used:

$.ajax("submit.php")
  .done(function(data) {
      //Ajax request was successful.
  })
  .fail(function(xhr, status, error) {
      //Ajax request failed.
      var errorMessage = xhr.status + ': ' + xhr.statusText
      alert('Error - ' + errorMessage);
})

Note that always is like complete, in the sense that it will always be called, regardless of whether the request was successful or not.

Hopefully, you found this tutorial to be useful.

Learn how to use the jQuery .get() method to make AJAX calls.

What you will learn ?

I’m going to show how to fetch contents from text files and database by using this method.

The full codes can be downloaded by the link given at the end of this tutorial.

In short: you will master this method.

The jQuery Get function is used to make AJAX calls and can be helpful to update a web page with partial page reloading. It uses HTTP GET method to initiate an AJAX request and fetch data from the external pages.

Let us understand all about this method in details.

Syntax of jQuery Get Method

jQuery.get( url [, data ] [, success ] [, dataType ] )

Parameters:

Name Value
url The URL to where the AJAX request of HTTP GET type is made. It is the Required parameter.
Data Optional parameter – the key-value pairs that will be send with the AJAX request. Eg {sport: “football”,player: “Cristiano Ronaldo”}
success(result,status,xhr) Optional Parameter – the function to call when the AJAX request is successful. All 3 parameters are optional. The result parameter will get the AJAX response.
dataType The Optional Parameter – the type of data returned from the AJAX response. It can be xml, json, script, text, or html

jQuery Get Method to Fetch Contents of a Text File

Let’s fetch a text file’s content with the jQuery Get method:

<button id="loadTextFile">Try</button>
<div id="textData"></div>
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $.get("file.txt", function (result, status, xhr) {
            $("#textData").html(result);
        });    
    });
</script>

The jQuery .get() method makes the AJAX call to the file.txt and shows it’s contents inside a div called textData.

Not just a text file, the above code can be use to fetch contents of other file types, like HTML, JSON, XML, etc.

Capturing jQuery Get Error

Use .fail() to capture any errors that come during the AJAX request.

See the below code:

<button id="loadNoTextFile">Try</button>
<div id="textNoData"></div>
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $("#loadNoTextFile").click(function (e) {
            $.get("no-file.txt", function (result, status, xhr) {
                $("#textNoData").html(result);
            }).fail(function (xhr, status, error) {
            $("#textNoData").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
        });
    }); 
</script>

In the above code, when trying to access a non-existing file, the .fail() function is called and it shows the message – Result: error Not Found 404 Not Found.

jQuery Get method to Fetch Data from Database

With the jQuery Get method you can make AJAX calls to a server page also. This server page in turn fetches data from the Database and returns it back as an AJAX response.

Let us create a small demo application in ASP.NET Web Forms to understand this feature.

jQuery Get Demo Application

There are 2 pages – one is HTML and other is .ASPX. The HTML page has 3 controls – 2 selects and a button.

On clicking the button, the 2 ‘select’ control values are passed to the .ASPX page by the jQuery Get method.

The HTML page code:

<div id="message"></div>
<select id="sportSelect">
    <option value="Select">Select Sports</option>
    <option value="Tennis">Tennis</option>
    <option value="Football">Football</option>
    <option value="Cricket">Cricket</option>
</select>
<select id="playerSelect">
    <option value="Select">Select Sports Person</option>
    <option value="Maria Sharapova">Maria Sharapova</option>
    <option value="Cristiano Ronaldo">Cristiano Ronaldo</option>
    <option value="Sachin Tendulkar">Sachin Tendulkar</option>
</select>
 
<button id="loadDatabase">Try</button>
<div id="dbData"></div>

The jQuery Code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
    $("#loadDatabase").click(function (e) {
        $.get("result.aspx",
            {
                sport: $("#sportSelect").val(),
                player: $("#playerSelect").val()
            },
            function (result, status, xhr) {
                $("#dbData").html(result);
            }).fail(function (xhr, status, error) {
                $("#dbData").html("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
        });
    });
</script>

In the .ASPX page, I get these 2 select control values, using Request.QueryString method.

I then fetch the respective data from the database.

Once I have the data from the DB then I use the Response.Write method to send it to the jQuery Get method as AJAX response.

The .ASPX page code:

List<MyDataBase> myDataBase;
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        LoadData();
        SearchDatabase();
    }
}
 
void SearchDatabase()
{
    string sport = Request.QueryString["sport"];
    string player = Request.QueryString["player"];
    try
    {
        string information = myDataBase.FirstOrDefault(x => x.sport == sport & x.player == player).information;
        Response.Write(information);
        Response.End();
    }
    catch (Exception ex)
    {
        Response.Write("NO DATA");
        Response.End();
    }
}
 
void LoadData()
{
    myDataBase = new List<MyDataBase>();
    myDataBase.Add(new MyDataBase() { sport = "Tennis", player = "Maria Sharapova", information = "Maria Sharapova is a...});
    myDataBase.Add(new MyDataBase() { sport = "Football", player = "Cristiano Ronaldo", information = "Cristiano Ronaldo is a..." });
    myDataBase.Add(new MyDataBase() { sport = "Cricket", player = "Sachin Tendulkar", information = "Sachin Tendulkar is a..." });
}
 
class MyDataBase
{
    public string sport { get; set; }
    public string player { get; set; }
    public string information { get; set; }
}

Instead of a Database, I have used a list type object which contains some dummy data. The ‘LoadData()’ function adds these dummy data to the list.

Download the source codes and check the download link:

DOWNLOAD

Conclusion

You are now ready to use the .get() method to make any type of AJAX feature in your website. Also check other similar topics in jQuery AJAX:

  • 1. jQuery AJAX Events
  • 2. jQuery AJAX
  • 3. jQuery Load
  • 4. jQuery Post

In this post we will show you how to jQuery ajax error function when Ajax decision passing information to a page that then returns a worth(value).

I have retrieved the self-made decision from the page however I even have coded it so it raises an erreo(bug) within the your call page(example url: "data.php"). however do we retrieve that error from the jquery? how we get jQuery Ajax Error Handling Function hear is the solution of ajax error function.

this jQuery ajax error function is very basic and easy to use with your ajax call.

$.ajax({
type: "POST",
url: "data.php",
data: { search: '1',keyword : 'somedata'},
cache: false,
success: function(data)
{
// success alert message
alert(data);
},
error: function (error)
{
// error alert message
alert('error :: ' + eval(error));
}
});

jQuery ajax error function using jqXHR

jQuery ajax error function using jqXHR in this function we can get different type ajax error like 404 page error, 500 Internal Server error, Requested JSON parse, Time out error.

$.ajax({
type: "POST",
url: "data.php",
data: { search: '1',keyword : 'somedata'},
cache: false,
success: function(data)
{
// success alert message
alert(data);
},
error: function (jqXHR, exception) {
var error_msg = '';
if (jqXHR.status === 0) {
error_msg = 'Not connect.n Verify Network.';
} else if (jqXHR.status == 404) {
// 404 page error
error_msg = 'Requested page not found. [404]';
} else if (jqXHR.status == 500) {
// 500 Internal Server error
error_msg = 'Internal Server Error [500].';
} else if (exception === 'parsererror') {
// Requested JSON parse
error_msg = 'Requested JSON parse failed.';
} else if (exception === 'timeout') {
// Time out error
error_msg = 'Time out error.';
} else if (exception === 'abort') {
// request aborte
error_msg = 'Ajax request aborted.';
} else {
error_msg = 'Uncaught Error.n' + jqXHR.responseText;
}
// error alert message
alert('error :: ' + error_msg);
},
});

Parameters for jQuery ajax error function with jqXHR

Parameters for jQuery ajax error function with jqXHR for It actually an error object which is looks like this.

jQuery ajax error function with an validation error

jQuery ajax error function with an validation error :: If we want to inform(get error message) in frontend about an validation error try this method.

$.ajax({
type: "POST",
url: "data.php",
data: { search: '1',keyword : 'somedata'},
cache: false,
success: function(data, textStatus, jqXHR) {
console.log(data.error);
}
});

jQuery.get()

JQ Home  << 
Ajax  << 
jQuery.get()

Asynchronous HTTP (Ajax) load request.

Description

The jQuery.get() Ajax method, allows us to load data from the server, using a HTTP GET request.

Shorthand version $.get()

  • Browsers operate the ‘same origin policy’, which means a request can not successfully retrieve data from a different domain, subdomain, or protocol. jQuery ‘Ajax’ requests are subject to this security restriction,
    the exceptions being requests made with a datatype of ‘script’ or ‘jsonp’.
  • The jQuery.get() method returns a jqXHR object which is a superset of the browser’s native XMLHttpRequest object. The jqXHR object implements the
    Promise interface, giving it all the properties, methods, and behavior of a Promise. See the lesson on the Deferred object for
    details of this. For standardization with the the Deferred object, the jqXHR object also provides done(), fail() and always() methods. These methods take a function argument that is called when the jQuery.get() request terminates and the function receives the same arguments as the same-named success(), error() and complete() setting callbacks respectively. This allows assignment of multiple callbacks for a single request as well as assigning callbacks after the request has completed. For completed requests, the callback is fired immediately.

    • It should be noted that the success(), error() and complete() callbacks of the jqXHR object are deprecated from use on request completion from jQuery 1.8 and removed in jQuery 3.0. This is for completion processing only and the Ajax settings will still have these values. Best practice is to use done(), fail() and always() methods on request completion to future proof code or use the new then() and catch() methods for Promises/A+ compliance.
  • A jqXHR object will expose the following properties and methods for backward compatibility with the XMLHttpRequest object:
    jqXHR Object Description
    Methods
    abort() Cancels the currently executing request.
    getAllResponseHeaders() Returns a string containing the names and value of all response headers.
    getResponseHeader(name) Returns the value of the specified response headers.
    .overrideMimeType() Used in the beforeSend() callback function, to modify the response content-type header.
    setRequestHeader(name, value) Set a request header using the specified name and value.
    Properties
    readyState An integer indicating the current state of the request.
    responseText Underlying request responded with text.
    responseXML Underlying request responded with xml.
    status Response status code returned from the server.
    statusText Status text message returned by the response.

Syntax

Signature Description
jQuery.get( url [, data] [, function(data, textStatus, jqXHR)] [, dataType] ) Load data from the server, using a HTTP GET request.
jQuery.get( settings ) Load data from the server using a HTTP GET request, passing some request settings.

Parameters

Parameter Description Type
url A string containing the URL to send the request to. String
data An object or string sent to the server with the request.

  • Data sent to the server is appended to the URL as a query string. If the data parameter is an object map, it is converted to a string and url encoded before being appended to the URL.
String or
PlainObject
function(data, textStatus, jqXHR) A callback function executed when the request succeeds. Function
dataType The type of data expected from the server.

  • Default: Inferred based on the MIME type of the response (html, json, script, or xml).
  • From jQuery 3.0 When requesting a script on a domain other than the one that hosts the document, you must now explicitly specify dataType: "script" in the options when using jQuery.get() to prevent cross domain attacks.
String
settings Default settings can be set globally by using the jQuery.ajaxSetup() method but the settings as described in jQuery.ajax( settings ) can be useful for individual Ajax requests. Various dependant upon settings parameter.

Return

A jqXHR object.

jQuery.get( url [, data] [, function( data, textStatus, jqXHR)] [, dataType] ) ExamplesAjax  <<  Top

Load data from the server, using a HTTP GET request.

This is a shorthand Ajax function, which is equivalent to using the jQuery.ajax() method as follows:


$.ajax({
  type: 'GET',
  url: url,
  data: data,
  dataType: dataType,
});

In the example below when we press the left button the first time we use the jQuery.get() method in its simplest form just using a url and output some messages dependant upon request success.

When we press the right button the first time we use the jQuery.get() method with a url and a success handler and output some messages dependant upon request success.


$(function(){
  $('#btn1').one('click', function(){
    $.get( "../../../js/get1.js" )
      .done(function() { $('#div1').append('Request succeeded! <br>'); })
      .fail(function() { $('#div1').append('Request failed! <br>'); })
      .always(function() { $('#div1').append('Request ended! <br><br>'); 
    });
  });
  $('#btn2').one('click', function(){
    $.get( "../../../js/get1.js", function(data, textStatus, jqXHR) {
         $('#div1').append('The request was a success! <br>');
      })
      .done(function() { $('#div1').append('Request succeeded! <br>'); })
      .fail(function() { $('#div1').append('Request failed! <br>'); })
      .always(function() { $('#div1').append('Request ended! <br><br>'); 
    });
  });
});

/*
 * The code for the external Javascript file called from $.ajax() (url: "../../../js/get1.js")
 * is shown below.
 */
$(function(){
  var someText = 'Passing some text. ';
  $('#div1').append('Message from get1.js: ' + someText + '<br>');
});

div1. Some initial text.

jQuery.get( settings ) ExamplesAjax  <<  Top

Load data from the server using a HTTP GET request, passing some request settings.

This is a shorthand Ajax function, which is equivalent to using the jQuery.ajax() method as follows:


$.ajax({
  type: 'GET',
  url: url,
  dataType: dataType,
  error: callback
  success: callback
});

In the example below when we press the left button the first time we use the jQuery.get() using a url, dataType and error and success parameters and output a fail messages as the url doesn’t exist.

In the example below when we press the right button the first time we use the jQuery.get() using a url, dataType and error and success parameters and output a success message and the contents of the retrieved url.


$(function(){
  $('#btn10').one('click', function(){
    $.get({
      url: "../../../js/get22.js",
      dataType: "script",
      error: function() { 
        $('#div2').append('The request failed! <br><br>');
      },
      success: function() { 
        $('#div2').append('The request was a sucesss! <br><br>');
      }
    });
  });

  $('#btn11').one('click', function(){
    $.get({
      url: "../../../js/get2.js",
      dataType: "script",
      error: function() { 
        $('#div2').append('The request failed! <br><br>');
      },
      success: function() { 
        $('#div2').append('The request was a sucesss! <br><br>');
      }
    });
  });


/*
 * The code for the external Javascript file called from $.ajax() (url: "../../../js/get2.js")
 * is shown below.
 */
$(function(){
  var someText = 'Passing some text. ';
  $('#div2').append('Message from get2.js: ' + someText + '<br>');
});

div2. Some initial text.

Related Tutorials

jQuery Advanced Tutorials — Lesson 9 — Ajax Shorthand Methods

  • Связанные категории:
  • Ajax
    » Shorthand Methods

Returns: jqXHR

Загружает данные с сервера, используя HTTP GET запрос.

  • version added: 1.0jQuery.get( url [, data] [, success(data, textStatus, jqXHR)] [, dataType] )

    url
    Тип: строка
    Адрес, на который отправляется запрос.

    data
    Тип: объект или строка
    Данные, отправляемые на сервер в виде объекта (ключ:значение) или строки.

    success(data, textStatus, jqXHR)
    Тип: функция
    Функция, вызываемая при успешном завершении Ajax запроса.

    dataType
    Тип: строка
    Тип данных, ожидаемых в качестве ответа от сервера. По умолчанию jQuery определит сам.

$.get() эквивалетна:

$.ajax({
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

Функция обратного вызова success, принимает ответ от сервера, который может быть в виде XML, строки, JavaScript файла или объекта JSON, в зависимости от MIME типа ответа. Это значение так же помещается в статус ответа.

Начиная с версии 1.5, функция обратного вызова success принимает объект jqXHR (в ранних версиях объект XMLHttpRequest). В случае использования JSONP, значение второго и третьего параметры функции будет неопределённым (undefined), т.к. при кросс-доменных GET запросах, объект XHR не используется.

$.get('ajax/test.html', function(data) {
  $('.result').html(data);
  alert('Загрузка завершена.');
});

Данный код делает запрос к HTML файлу и выводит его содержимое.

Объект jqXHR

Начиная с версии 1.5, $.get() возвращает объект jqXHR, реализующий интерфейс deferred, что позволяет задавать дополнительные обработчики. Помимо стандартных для объекта deferred методов .done(), .fail() и .then(), с помощью которых можно устанавливать обработчики, в jqXHR реализованы их копии: .success(), .error() и .complete(). Это сделано для соответствия привычным названиям методов, с помощью которых устанавливаются обработчики выполнения ajax-запросов.

// запускаем ajax-запрос, устанавливаем обработчики событий.
// Возвращаемые методом $.get объект сохраним в переменной jqxhr для дальнейшего использования
var jqxhr = $.get("example.php", function() {
  alert("success");
})
.done(function() { alert("second success"); })
.fail(function() { alert("error"); })
.always(function() { alert("finished"); });
 
// установим еще один обработчик завершения запроса
jqxhr.always(function(){ alert("second finished"); });

Заметка об устаревших методах

Функции обратного действия, введённые в jQuery 1.5 устарени в версии 1.8. Вместо jqXHR.success(), jqXHR.error() и jqXHR.complete() теперь следует использовать jqXHR.done(), jqXHR.fail() и jqXHR.always().

Примеры

Сделать запрос к test.php, игнорируя ответ:

$.get("test.php");

Сделать запрос к test.php, передать данные, игнорировать ответ:

$.get("test.php", { name: "John", time: "2pm" } );

Передать массив данных на сервер, игнорируя ответ:

$.get("test.php", { 'choices[]': ["Jon", "Susan"]} );

Обработать ответ от сервера (HTML или XML в зависимости от того, что пришло):

$.get("test.php", function(data) {
  alert("Data Loaded: " + data);
});

Сделать запрос к test.cgi, предать данные, обработать ответ (HTML или XML в зависимости от того, что пришло):

$.get("test.cgi", { name: "John", time: "2pm" })
.done(function(data) {
  alert("Data Loaded: " + data);
});

Получить от сервера ответ в JSON формате и вывести его на страницу (<?php echo json_encode(array(«name»=>»John»,»time»=>»2pm»)); ?>):

$.get("test.php",
   function(data) {
     $('body').append( "Name: " + data.name ) // John
              .append( "Time: " + data.time ); //  2pm
   }, "json");

Связанные уроки:

  • Желтые стикеры с помощью AJAX, PHP и jQuery

    Сегодня мы создаем систему управления желтыми стикерами.

  • Что нового в jQuery 1.5?

    Совсем недавно, как и было обещано, группа разработчиков библиотеки jQuery выпустила новую версию своего продукта. Я попытаюсь вам рассказать о фитчах, которые вошли в свежий релиз.

import jQuery from «./core.js»; import document from «./var/document.js»; import rnothtmlwhite from «./var/rnothtmlwhite.js»; import location from «./ajax/var/location.js»; import nonce from «./ajax/var/nonce.js»; import rquery from «./ajax/var/rquery.js»; import «./core/init.js»; import «./core/parseXML.js»; import «./event/trigger.js»; import «./deferred.js»; import «./serialize.js»; // jQuery.param var r20 = /%20/g, rhash = /#.*$/, rantiCache = /([?&])_=[^&]*/, rheaders = /^(.*?):[ t]*([^rn]*)$/mg, // trac-7653, trac-8125, trac-8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^///, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * — BEFORE asking for a transport * — AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol «*» can be used * 5) execution will start with transport dataType and THEN continue down to «*» if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol «*» can be used * 3) selection will start with transport dataType and THEN go to «*» if needed */ transports = {}, // Avoid comment-prolog char sequence (trac-10098); must appease lint and evade compression allTypes = «*/».concat( «*» ), // Anchor tag for parsing the document origin originAnchor = document.createElement( «a» ); originAnchor.href = location.href; // Base «constructor» for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to «*» return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== «string» ) { func = dataTypeExpression; dataTypeExpression = «*»; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( rnothtmlwhite ) || []; if ( typeof func === «function» ) { // For each dataType in the dataTypeExpression while ( ( dataType = dataTypes[ i++ ] ) ) { // Prepend if requested if ( dataType[ 0 ] === «+» ) { dataType = dataType.slice( 1 ) || «*»; ( structure[ dataType ] = structure[ dataType ] || [] ).unshift( func ); // Otherwise append } else { ( structure[ dataType ] = structure[ dataType ] || [] ).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if ( typeof dataTypeOrTransport === «string» && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } } ); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ «*» ] && inspect( «*» ); } // A special extend for ajax options // that takes «flat» options (not to be deep extended) // Fixes trac-9887 function ajaxExtend( target, src ) { var key, deep, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } /* Handles responses to an ajax request: * — finds the right dataType (mediates between content-type and expected dataType) * — returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var ct, type, finalDataType, firstDataType, contents = s.contents, dataTypes = s.dataTypes; // Remove auto dataType and get content-type in the process while ( dataTypes[ 0 ] === «*» ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader( «Content-Type» ); } } // Check if we’re dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + » « + dataTypes[ 0 ] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } /* Chain conversions given the request and the original response * Also sets the responseXXX fields on the jqXHR instance */ function ajaxConvert( s, response, jqXHR, isSuccess ) { var conv2, current, conv, tmp, prev, converters = {}, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(); // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } current = dataTypes.shift(); // Convert to each sequential dataType while ( current ) { if ( s.responseFields[ current ] ) { jqXHR[ s.responseFields[ current ] ] = response; } // Apply the dataFilter if provided if ( !prev && isSuccess && s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } prev = current; current = dataTypes.shift(); if ( current ) { // There’s only work to do if current dataType is non-auto if ( current === «*» ) { current = prev; // Convert response if prev dataType is non-auto and differs from current } else if ( prev !== «*» && prev !== current ) { // Seek a direct converter conv = converters[ prev + » « + current ] || converters[ «* « + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split( » « ); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + » « + tmp[ 0 ] ] || converters[ «* « + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.unshift( tmp[ 1 ] ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s.throws ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: «parsererror», error: conv ? e : «No conversion from « + prev + » to « + current }; } } } } } } return { state: «success», data: response }; } jQuery.extend( { // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: location.href, type: «GET», isLocal: rlocalProtocol.test( location.protocol ), global: true, processData: true, async: true, contentType: «application/x-www-form-urlencoded; charset=UTF-8», /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { «*»: allTypes, text: «text/plain», html: «text/html», xml: «application/xml, text/xml», json: «application/json, text/javascript» }, contents: { xml: /bxmlb/, html: /bhtml/, json: /bjsonb/ }, responseFields: { xml: «responseXML», text: «responseText», json: «responseJSON» }, // Data converters // Keys separate source (or catchall «*») and destination types with a single space converters: { // Convert anything to text «* text»: String, // Text to html (true = no transformation) «text html»: true, // Evaluate text as a json expression «text json»: JSON.parse, // Parse text as xml «text xml»: jQuery.parseXML }, // For options that shouldn’t be deep extended: // you can add your own custom options here if // and when you create one that shouldn’t be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === «object» ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var transport, // URL without anti-cache param cacheURL, // Response headers responseHeadersString, responseHeaders, // timeout handle timeoutTimer, // Url cleanup var urlAnchor, // Request state (becomes false upon send and true upon completion) completed, // To know if global events are to be dispatched fireGlobals, // Loop variable i, // uncached part of the url uncached, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks( «once memory» ), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // Default abort message strAbort = «canceled», // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( completed ) { if ( !responseHeaders ) { responseHeaders = {}; while ( ( match = rheaders.exec( responseHeadersString ) ) ) { // Support: IE 11+ // `getResponseHeader( key )` in IE doesn’t combine all header // values for the provided key into a single result with values // joined by commas as other browsers do. Instead, it returns // them on separate lines. responseHeaders[ match[ 1 ].toLowerCase() + » « ] = ( responseHeaders[ match[ 1 ].toLowerCase() + » « ] || [] ) .concat( match[ 2 ] ); } } match = responseHeaders[ key.toLowerCase() + » « ]; } return match == null ? null : match.join( «, « ); }, // Raw string getAllResponseHeaders: function() { return completed ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { if ( completed == null ) { name = requestHeadersNames[ name.toLowerCase() ] = requestHeadersNames[ name.toLowerCase() ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( completed == null ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( completed ) { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } else { // Lazy-add the new callbacks in a way that preserves old ones for ( code in map ) { statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ); // Add protocol if not provided (prefilters might expect it) // Handle falsy url in the settings object (trac-10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || location.href ) + «» ) .replace( rprotocol, location.protocol + «//» ); // Alias method option to type as per ticket trac-12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = ( s.dataType || «*» ).toLowerCase().match( rnothtmlwhite ) || [ «» ]; // A cross-domain request is in order when the origin doesn’t match the current origin. if ( s.crossDomain == null ) { urlAnchor = document.createElement( «a» ); // Support: IE <=8 — 11+ // IE throws exception on accessing the href property if url is malformed, // e.g. http://example.com:80x/ try { urlAnchor.href = s.url; // Support: IE <=8 — 11+ // Anchor’s host property isn’t correctly set when s.url is relative urlAnchor.href = urlAnchor.href; s.crossDomain = originAnchor.protocol + «//» + originAnchor.host !== urlAnchor.protocol + «//» + urlAnchor.host; } catch ( e ) { // If there is an error parsing the URL, assume it is crossDomain, // it can be rejected by the transport if it is invalid s.crossDomain = true; } } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== «string» ) { s.data = jQuery.param( s.data, s.traditional ); } // If request was aborted inside a prefilter, stop there if ( completed ) { return jqXHR; } // We can fire global events as of now if asked to // Don’t fire events if jQuery.event is undefined in an ESM-usage scenario (trac-15118) fireGlobals = jQuery.event && s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger( «ajaxStart» ); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we’re toying with the If-Modified-Since // and/or If-None-Match header later on // Remove hash to simplify url manipulation cacheURL = s.url.replace( rhash, «» ); // More options handling for requests with no content if ( !s.hasContent ) { // Remember the hash so we can put it back uncached = s.url.slice( cacheURL.length ); // If data is available and should be processed, append data to url if ( s.data && ( s.processData || typeof s.data === «string» ) ) { cacheURL += ( rquery.test( cacheURL ) ? «&» : «?» ) + s.data; // trac-9682: remove data so that it’s not used in an eventual retry delete s.data; } // Add or update anti-cache param if needed if ( s.cache === false ) { cacheURL = cacheURL.replace( rantiCache, «$1» ); uncached = ( rquery.test( cacheURL ) ? «&» : «?» ) + «_=» + ( nonce.guid++ ) + uncached; } // Put hash and anti-cache on the URL that will be requested (gh-1732) s.url = cacheURL + uncached; // Change ‘%20’ to ‘+’ if this is encoded form body content (gh-2658) } else if ( s.data && s.processData && ( s.contentType || «» ).indexOf( «application/x-www-form-urlencoded» ) === 0 ) { s.data = s.data.replace( r20, «+» ); } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( «If-Modified-Since», jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( «If-None-Match», jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( «Content-Type», s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( «Accept», s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[ 0 ] ] ? s.accepts[ s.dataTypes[ 0 ] ] + ( s.dataTypes[ 0 ] !== «*» ? «, « + allTypes + «; q=0.01» : «» ) : s.accepts[ «*» ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || completed ) ) { // Abort if not done already and return return jqXHR.abort(); } // Aborting is no longer a cancellation strAbort = «abort»; // Install callbacks on deferreds completeDeferred.add( s.complete ); jqXHR.done( s.success ); jqXHR.fail( s.error ); // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( 1, «No Transport» ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( «ajaxSend», [ jqXHR, s ] ); } // If request was aborted inside ajaxSend, stop there if ( completed ) { return jqXHR; } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = window.setTimeout( function() { jqXHR.abort( «timeout» ); }, s.timeout ); } try { completed = false; transport.send( requestHeaders, done ); } catch ( e ) { // Rethrow post-completion exceptions if ( completed ) { throw e; } // Propagate others as results done( 1, e ); } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Ignore repeat invocations if ( completed ) { return; } completed = true; // Clear timeout if it exists if ( timeoutTimer ) { window.clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || «»; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Determine if successful isSuccess = status >= 200 && status < 300 || status === 304; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // Use a noop converter for missing script but not if jsonp if ( !isSuccess && jQuery.inArray( «script», s.dataTypes ) > 1 && jQuery.inArray( «json», s.dataTypes ) < 0 ) { s.converters[ «text script» ] = function() {}; } // Convert no matter what (that way responseXXX fields are always set) response = ajaxConvert( s, response, jqXHR, isSuccess ); // If successful, handle type chaining if ( isSuccess ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader( «Last-Modified» ); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader( «etag» ); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 || s.type === «HEAD» ) { statusText = «nocontent»; // if not modified } else if ( status === 304 ) { statusText = «notmodified»; // If we have data, let’s convert it } else { statusText = response.state; success = response.data; error = response.error; isSuccess = !error; } } else { // Extract error from statusText and normalize for non-aborts error = statusText; if ( status || !statusText ) { statusText = «error»; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + «»; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? «ajaxSuccess» : «ajaxError», [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( «ajaxComplete», [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( jQuery.active ) ) { jQuery.event.trigger( «ajaxStop» ); } } } return jqXHR; }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, «json» ); }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, «script» ); } } ); jQuery.each( [ «get», «post» ], function( _i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // Shift arguments if data argument was omitted. // Handle the null callback placeholder. if ( typeof data === «function» || data === null ) { type = type || callback; callback = data; data = undefined; } // The url can be an options object (which then must have .url) return jQuery.ajax( jQuery.extend( { url: url, type: method, dataType: type, data: data, success: callback }, jQuery.isPlainObject( url ) && url ) ); }; } ); jQuery.ajaxPrefilter( function( s ) { var i; for ( i in s.headers ) { if ( i.toLowerCase() === «content-type» ) { s.contentType = s.headers[ i ] || «»; } } } ); export default jQuery;

Понравилась статья? Поделить с друзьями:
  • Jquery error is not a function
  • Jquery ajax success error
  • Jquery ajax post error ajax
  • Jquery ajax post error 500
  • Jquery ajax json error