Getjson on error

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

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

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

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

    • 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.

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

Data that is sent to the server is appended to the URL as a query string. If the value of the data parameter is a plain object, it is converted to a string and url-encoded before it is appended to the URL.

Most implementations will specify a success handler:

1

2

3

4

5

6

7

8

9

10

11

$.getJSON( "ajax/test.json", function( data ) {

$.each( data, function( key, val ) {

items.push( "<li id='" + key + "'>" + val + "</li>" );

This example, of course, relies on the structure of the JSON file:

1

2

3

4

5

"one": "Singular sensation",

"two": "Beady little eyes",

"three": "Little birds pitch by my doorstep"

Using this structure, the example loops through the requested data, builds an unordered list, and appends it to the body.

The success callback is passed the returned data, which is typically a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method. It is also passed the text status of the response.

As of jQuery 1.5, the success callback function receives a «jqXHR» object (in jQuery 1.4, it received 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.

Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript’s object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see https://json.org/.

JSONP

If the URL includes the string «callback=?» (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.

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 $.getJSON() 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 in jQuery 1.5 also allows jQuery’s Ajax methods, including $.getJSON(), to chain multiple .done(), .always(), and .fail() 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 = $.getJSON( "example.json", function() {

console.log( "success" );

console.log( "second success" );

console.log( "complete" );

// Perform other work here ...

// Set another completion function for the request above

jqxhr.always(function() {

console.log( "second complete" );

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.
  • Script and JSONP requests are not subject to the same origin policy restrictions.

Examples:

Loads the four most recent pictures of Mount Rainier from the Flickr JSONP API.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

<title>jQuery.getJSON demo</title>

<script src="https://code.jquery.com/jquery-3.6.3.js"></script>

var flickerAPI = "https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";

$.each( data.items, function( i, item ) {

$( "<img>" ).attr( "src", item.media.m ).appendTo( "#images" );

Demo:

Load the JSON data from test.js and access a name from the returned JSON data.

1

2

3

$.getJSON( "test.js", function( json ) {

console.log( "JSON Data: " + json.users[ 3 ].name );

Load the JSON data from test.js, passing along additional data, and access a name from the returned JSON data.
If an error occurs, log an error message instead.

1

2

3

4

5

6

7

8

$.getJSON( "test.js", { name: "John", time: "2pm" } )

console.log( "JSON Data: " + json.users[ 3 ].name );

.fail(function( jqxhr, textStatus, error ) {

var err = textStatus + ", " + error;

console.log( "Request Failed: " + err );

In this article, we’ll investigate the importance of JSON and why we should use it in our applications. We’ll see that jQuery has got us covered with a very nice convenience function.

What is JSON?

JSON stands for JavaScript Object Notation. It’s a language-independent, text-based format, which is commonly used for transmitting data in web applications. In this article, we’ll look at loading JSON data using an HTTP GET request (we can also use other verbs, such as POST).

Why would we choose JSON over say XML? The key advantage of using JSON is efficiency. JSON is less verbose and cluttered, resulting in fewer bytes and a faster parse process. This allows us to process more messages sent as JSON than as XML. Moreover, JSON has a very efficient and natural object representation leading to formats such as BSON, where JSON-like objects are stored in a binary format.

Now, let’s see how jQuery can help us load JSON-encoded data from a remote source. For the impatient among you, there’s a demo towards the end of the article.

JSON jQuery Syntax

The $.getJSON() method is a handy helper for working with JSON directly if you don’t require much extra configuration. Essentially, it boils down to the more general $.ajax() helper, with the right options being used implicitly. The method signature is:

$.getJSON(url, data, success);

Besides the required URL parameter, we can pass in two optional parameters. One represents the data to send to the server; the other one represents a callback to trigger in case of a successful response.

So the three parameters correspond to:

  • the url parameter, which is a string containing the URL to which the request is sent
  • the optional data parameter, which is either an object or a string that’s sent to the server with the request
  • the optional success(data, textStatus, jqXHR) parameter, which is a callback function executed only if the request succeeds

In the simplest scenario, we only care about the returned object. In this case, a potential success callback would look like this:

function success(data) {
  // do something with data, which is an object
}

As mentioned, the same request can be triggered with the more verbose $.ajax() call. Here we would use:

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

Let’s see this in practice using a little demo.

A Sample Application

We’ll start a local server that serves a static JSON file. The object represented by this file will be fetched and processed by our JavaScript code. For the purposes of our demo, we’ll use Node.js to provide the server (although any server will do). This means we’ll need the following three things:

  • a working installation of Node.js
  • the node package manager (npm)
  • a global installation of the live-server package

The first two points are platform-dependent. To install Node, please head to the project’s download page and grab the relevant binaries for your system. Alternatively, you might like to consider using a version manager as described in “Installing Multiple Versions of Node.js Using nvm”.

npm comes bundled with Node, so there’s no need to install anything. However, if you need any help getting up and running, consult our tutorial “A Beginner’s Guide to npm — the Node Package Manager”.

The third point can be achieved by running the following from your terminal:

npm install -g live-server

If you find yourself needing a sudo prefix (-nix systems) or an elevated command prompt to perform this global installation, you should consider changing the location of global packages.

Once these requirements have been met, we can create the following three files in a new folder:

  • main.js, which is the JavaScript file to request the data
  • example.json, which is the example JSON file
  • index.html, which is the HTML page to call the JavaScript and display the data

From the command prompt we can simply invoke live-server within the new folder. This will open our demo in a new browser tab, running at http://localhost:8080.

The Sample JavaScript

The following code is the complete client-side logic. It waits for the DOMContentLoaded loaded event to fire, before grabbing a reference to two DOM elements — $showData, where we’ll display the parsed response, and $raw, where we’ll display the complete response.

We then attach an event handler to the click event of the element with the ID get-data. When this element is clicked, we attempt to load the JSON from the server using $.getJSON(), before processing the response and displaying it on the screen:

$(document).ready(() => {
  const $showData = $('#show-data');
  const $raw = $('pre');

  $('#get-data').on('click', (e) => {
    e.preventDefault();

    $showData.text('Loading the JSON file.');

    $.getJSON('example.json', (data) => {
      const markup = data.items
        .map(item => `<li>${item.key}: ${item.value}</li>`)
        .join('');

      const list = $('<ul />').html(markup);

      $showData.html(list);

      $raw.text(JSON.stringify(data, undefined, 2));
    });
  });
});

Besides converting parts of the object to an unordered list, the full object is also stringified and displayed on the screen. The unordered list is added to a <div> element with the ID show-data, the JSON string a <pre> tag, so that it is nicely formatted. Of course, for our example the data is fixed, but in general any kind of response is possible.

Note that we also set some text for the output <div>. If we insert some (artificial) delay for the JSON retrieval (for example, in your browser’s dev tools), we’ll see that this actually executes before any result of the $.getJSON request is displayed. The reason is simple: by default, $.getJSON is non-blocking — that is, async. Therefore, the callback will be executed at some (unknown) later point in time.

Distilling the source to obtain the crucial information yields the following block:

$('#get-data').on('click', () => {
  $.getJSON('example.json', (data) => {
    console.log(data);
  });
});

Here we only wire the link to trigger the start of the $.getJSON helper before printing the returned object in the debugging console.

The Sample JSON

The sample JSON file is much larger than the subset we care about. Nevertheless, the sample has been constructed in such a way as to show most of the JSON grammar. The file reads:

{
  "items": [
    {
      "key": "First",
      "value": 100
    },
    {
      "key": "Second",
      "value": false
    },
    {
      "key": "Last",
      "value": "Mixed"
    }
  ],
  "obj": {
    "number": 1.2345e-6,
    "enabled": true
  },
  "message": "Strings have to be in double-quotes."
}

In the sample JavaScript, we’re only manipulating the array associated with the items key. In contrast to ordinary JavaScript, JSON requires us to place keys in double quotes. Additionally, we can’t use trailing commas for specifying objects or arrays. However, as with ordinary JavaScript arrays, we are allowed to insert objects of different types.

The Sample Web Page

We’ve already looked at the script and the sample JSON file. All that’s left is the web page, which provides the parts being used by the JavaScript file to trigger and display the JSON file:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Request JSON Test</title>
  </head>
  <body>
    <a href="#" id="get-data">Get JSON data</a>
    <div id="show-data"></div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="main.js"></script>
  </body>
</html>

There’s not much to say here. We use the minified version of jQuery from the official web page. Then we include our script, which is responsible for injecting the logic.

Note: as we’re including our JavaScript files in the correct place (just before the closing </body> tag), it no longer becomes necessary to use a $(document).ready() callback, because at this point, the document will be ready by definition.

Demo

And this is what we end up with.

The More General Method

As previously mentioned, the $.ajax method is the real deal for any (not only JSON-related) web request. This method allows us to explicitly set all the options we care about. We can adjust async to true if we want this to call to run concurrently — that is, run potentially at the same time as other code. Setting it to false will prevent other code from running while the download is in progress:

$.ajax({
  type: 'GET',
  url: filename,
  data: data,
  async: false,
  beforeSend: (xhr) => {
    if (xhr && xhr.overrideMimeType) {
      xhr.overrideMimeType('application/json;charset=utf-8');
    }
  },
  dataType: 'json',
  success: (data) => {
    //Do stuff with the JSON data
  }
});

The overrideMimeType method (which overrides the MIME type returned by the server) is only called for demonstration purposes. Generally, jQuery is smart enough to adjust the MIME-type according to the used data type.

Before we go on to introduce the concept of JSON validation, let’s have short look at a more realistic example. Usually, we won’t request a static JSON file, but will load JSON, which is generated dynamically (for example, as the result of calling an API). The JSON generation is dependent on some parameter(s), which have to be supplied beforehand:

const url = 'https://api.github.com/v1/...';
const data = {
  q: 'search',
  text: 'my text'
};

$.getJSON(url, data, (data, status) => {
  if (status === 200) {
    //Do stuff with the JSON data
  }
});

Here we check the status to ensure that the result is indeed the object returned from a successful request and not some object containing an error message. The exact status code is API-dependent, but for most GET requests, a status code of 200 is usual.

The data is supplied in the form of an object, which leaves the task of creating the query string (or transmitting the request body) up to jQuery. This is the best and most reliable option.

JSON Validation

We shouldn’t forget to validate our JSON data! There’s an online JSON Validator tool called JSONLint that can be used to validate JSON files. Unlike JavaScript, JSON is very strict and doesn’t have tolerances — for example, for the aforementioned trailing commas or multiple ways of writing keys (with /, without quotes).

So, let’s discuss some of the most common errors when dealing with JSON.

Common $.getJSON errors

  • Silent failures on $.getJSON calls. This might happen if, for example, jsoncallback=json1234 has been used, while the function json1234() doesn’t exist. In such cases, the $.getJSON will silently error. We should therefore always use jsoncallback=? to let jQuery automatically handle the initial callback.
  • In the best case, real JSON (instead of JSONP) is used (either by talking with our own server or via CORS). This eliminates a set of errors potentially introduced by using JSONP. The crucial question is: Does the server / API support JSONP? Are there any restrictions on using JSONP? You can find out more about working with JSONP here.
  • Uncaught syntax error: Unexpected token (in Chrome) or invalid label (in Firefox). The latter can be fixed by passing the JSON data to the JavaScript callback. In general, however, this is a strong indicator that the JSON is malformed. Consider using JSONLint, as advised above.

The big question now is: How do we detect if the error actually lies in the transported JSON?

How to fix JSON errors

There are three essential points that should be covered before starting any JSON-related debugging:

  • We have to make sure that the JSON returned by the server is in the correct format with the correct MIME-type being used.
  • We can try to use $.get instead of $.getJSON, as it might be that our server returns invalid JSON. Also, if JSON.parse() fails on the returned text, we immediately know that the JSON is to blame.
  • We can check the data that’s being returned by logging it to the console. This should then be the input for further investigations.

Debugging should then commence with the previously mentioned JSONLint tool.

Conclusion

JSON is the de-facto standard format for exchanging text data. jQuery’s $.getJSON() method gives us a nice little helper to deal with almost any scenario involving a request for JSON formatted data. In this article, we’ve investigated some methods and possibilities that come with this handy helper.

If you need help implementing JSON fetching in your code (using $.getJSON() or anything else), come and visit us in the SitePoint forums.

jQuery is the most awesome javascript library that exists. Every day, I’m finding new ways to leverage it and shorter, more efficient ways to get things done. But, while most things are easy to do, the solution is not always immediately evident. One of the things that took me a good while to figure out was how to gracefully handle AJAX errors. Anyone who’s worked with JSON requests and other AJAX calls knows that sometimes, that stuff just fails silently; you know something went wrong, but no errors were thrown. If it wasn’t for FireBug showing us 404 or 500 style errors, there’d be no evidence at all of these fails.

I’ve come up with a way to centralize my AJAX calls in a way that seemlessly handles all errors that occur either from the request connection or the JSON processing (ie. poorly formed JSON that cannot be converted back into Javascript data types). I’m not sure if this is the best of all ways, but I’m liking it. The whole concept rests on the fact that all of my system API (AJAX) calls return a uniform response with the following structure:

{
	SUCCESS: true,
	DATA: "",
	ERRORS: []
}

The Success property flags the request as having executed properly and returned the expected data. The Data property can be anything it needs to be. The Errors property is an array of any errors that need to be reported. It is only by requiring that all AJAX requests expect this that I can easily handle all errors.

In production, the following code would probably be part of some other object or integrated into the Javascript framework in a different way, but for this demo, I’m going to break out my AJAX request pipeline into its own class:

// Create an object to handle our AJAX.
function AJAX(){
	var objSelf = this;

	// This struct will cache the current XmlHTTP requests
	// so that we can reference them if a call fails.
	this.CurrentRequests = {};
}


// This handles the JSON request. This checks to see if the current
// request is already being processed and also handles any error
// wiring that is required.
AJAX.prototype.GetJSON = function( $1, $2, $3, $4 ){
	var objSelf = this;
	var strName = $1;
	var strURL = $2;
	var objOptions = $3;
	var fnCallback = $4;

	// Check to see if there are only three arguments. If there
	// are only 3, then the first one (name of request) which is
	// optional was not passed in. Shift the other arguments
	// to the appropriate variables.
	if (arguments.length == 3){

		// Name is not being used.
		strName = null;
		strURL = $1;
		objOptions = $2;
		fnCallback = $3;

	}

	// First, we have to check to see if this request is
	// already being processed. We don't want the user to
	// try and fire off multiple requests of the same type.
	// Of course, if the name is NULL, then don't worry.
	if (!strName || !this.CurrentRequests[ strName ]){

		// Store current request.
		this.CurrentRequests[ strName ] = true;

		// Make actual AJAX request.
		$.ajax(
			{
				// Basic JSON properties.
				url: strURL,
				data: objOptions,
				dataType: "json",

				// The success call back.
				success: function( objResponse ){
					// Remove request flag.
					objSelf.CurrentRequests[ strName ] = false;

					// Pass off to success handler.
					fnCallback( objResponse );
				},

				// The error handler.
				error: function( objRequest ){
					// Remove request flag.
					objSelf.CurrentRequests[ strName ] = false;

					// Pass off to fail handler.
					objSelf.AJAXFailHandler(
						objRequest,
						fnCallback
						);
				}
			}
			);

	} else {

		// This request is currently being processed.
		alert( "Request being processed. Be patient." );

	}
}


// This will handle all AJAX failures.
AJAX.prototype.AJAXFailHandler = function( objRequest, fnCallback ){
	// Since this AJAX request failed, let's call the callback
	// but manually create a failure response.
	fnCallback(
		{
			SUCCESS: false,
			DATA: "",
			ERRORS: [ "Request failed" ]
		}
		);
}

(I’m sorry the color coding doesn’t work for my Javascript files) There’s not a whole lot going on here, but let’s walk through it. First off, one thing you can do here is make sure that only one AJAX request (of a particular type) can be processed at a time. The GetJSON() method here can take 3 or 4 arguments. If you pass in the first, optional argument — the name of the request — the GetJSON() logic will make sure that it does not launch multiple instances of the same type of AJAX request at any one time. If you pass in only the three required fields, the GetJSON() method will allow parallel AJAX requests of the same type. You will see this in the demo below — I serialize my 200 requests but allow my 404 requests to happen in parallel.

The methodology that I use leverages the $.ajax() jQuery method. I used to just use the $.getJSON() method of the jQuery library, but the $.ajax() method gives us access to the Error call back method of the AJAX request. With this method and my unified AJAX response, handling errors is actually quite easy. All AJAX errors are piped through my AJAXFailHandler() method which creates a «fail» AJAX response (sets SUCCESS flag to false) and then manually executes the AJAX callback, passing in the fail response. This way, from the AJAX response handler’s point of view, it has no idea that anything has gone wrong — it only knows that it received a response object that was either flagged as a success or a failure.

Now, let’s take a look at the demo page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
	<title>Handling AJAX Errors With jQuery</title>
	<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
	<script type="text/javascript" src="script.js"></script>
	<script type="text/javascript">

		// Initialize document.
		$(
			function(){
				var objAJAX = new AJAX();

				// Get reference to the three links.
				var j404 = $( "#error-404" );
				var jNoError = $( "#no-error" );

				// Set up 404 link.
				j404
					.attr( "href", "javascript:void(0)" )
					.click(
						function( objEvent ){
							// Make AJAX request.
							objAJAX.GetJSON(
								"does-not-exist.cfm",
								{},
								Do404RequestHandler
								);

							// Prevent default.
							objEvent.preventDefault();
							return( false );
						}
						)
				;

				// Set up no-error link.
				jNoError
					.attr( "href", "javascript:void(0)" )
					.click(
						function( objEvent ){
							// Make AJAX request.
							objAJAX.GetJSON(
								"NoErrorRequest",
								"200.cfm",
								{},
								NoErrorRequestHandler
								);

							// Prevent default.
							objEvent.preventDefault();
							return( false );
						}
						)
				;
			}
			);


		// I handle the 404 request repsonse.
		function Do404RequestHandler( objResponse ){
			// Check to see if request was successful.
			if (objResponse.SUCCESS){

				alert( "Success!" );

			} else {

				alert( "404 Error!" );
			}
		}


		// I handle the no-error request repsonse.
		function NoErrorRequestHandler( objResponse ){
			// Check to see if request was successful.
			if (objResponse.SUCCESS){

				alert( "Success!" );

			} else {

				alert( "No-Error Error!" );
			}
		}

	</script>
</head>
<body>

	<h1>
		Handling AJAX Errors With jQuery
	</h1>

	<p>
		<a id="error-404">404 Error</a> &nbsp;|&nbsp;
		<a id="no-error">Success</a>
	</p>

</body>
</html>

As you can see above, we are using jQuery to hook the links up to launch AJAX calls. Each of the two links — 404 and 200 responses — has its own response handler method. These methods, check to see if the response object was successful and just alerts the user. Notice that only the 200 style request passes in the name of the request, «NoErrorRequest»; this will ensure that the 200 style requests are serialized. The 404 style request, on the other hand, does not label its AJAX requests and therefore can make as many parallel requests as it likes.

I’m sure that I will continue to evolve the way I handle these situations over time, but so far, I have been really pleased with this methodology. It completely differentiates the two types of AJAX errors — logical vs. critical — and moves all critical error handling out of the business logic of the application.

If you are curious to see what is happening at the other end of the 200.cfm request, here is that template:

<!--- Create the response. --->
<cfset objResponse = {
	Success = true,
	Data = "Good request",
	Errors = []
	} />

<!--- Serialize the response. --->
<cfset strJSON = SerializeJSON( objResponse ) />

<!--- Get the binary response. --->
<cfset binJSON = ToBinary( ToBase64( strJSON ) ) />

<!--- Stream it back. --->
<cfheader
	name="content-length"
	value="#ArrayLen( binJSON )#"
	/>

<cfcontent
	type="text/json"
	variable="#binJSON#"
	/>

As you can see, it simply creates my unified AJAX response object and streams it back to the client.

Want to use code from this post?
Check out the license.

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!

Это сокращенная Ajax функция, которая эквивалентна следующему коду:

Данные отправляемые на сервере передаются в URL строке как GET параметры. Если значением параметра data является объект (не строка), то он конвертируется в строку (с предварительным url-encode кодированием значений) перед добвлением к URL адресу.

В большинстве случаев, обработчик success указывается:

1

2

3

4

5

6

7

8

9

10

11

$.getJSON( "ajax/test.json", function( data ) {

$.each( data, function( key, val ) {

items.push( "<li id='" + key + "'>" + val + "</li>" );

Этот пример, конечно, зависит от структуры запрошенного JSON файла:

1

2

3

4

5

"one": "Singular sensation",

"two": "Beady little eyes",

"three": "Little birds pitch by my doorstep"

Используя такую структуру, в примере происходит перебор запрошенных данных, строится неупорядоченный список и добавляет его к body.

В функцию обратного вызова success передаются возвращенные данные с сервера, которые обычно представляют из себя JavaScript объект или массив, соотвествующий формату JSON, — полученные при помощи метода $.parseJSON(). Также передается текстовый статус ответа.

Начиная с jQuery 1.5, функция success принимает объект «jqXHR» object (в jQuery 1.4, она принимает объект XMLHttpRequest). Однако, так как JSONP и кросс-доменные запросы не используют XHR, то в этом случае параметры jqXHR и textStatus не будут переданы в функцию success.

Важно: начиная с jQuery 1.4, если JSON файл содержит синтаксические ошибки, для запроса просто вызовется обработчик ошибки (если он установлен). По этой причине, избегайте руного редактирования JSON данных. JSON представляет из себя формат обмена данных с правилами синтаксиса более жесткими чем правила определения для JavaScript объектов. Например, все строки представленные в JSON, являются ли они свойством или значением, должны быть заключены в двойные кавычки. Уточните информацию о формате JSON по ссылке http://json.org/.

JSONP

Если в URL адрес включена строка «callback=?» (или подобные, как это определяет серверное API), запрос обрабатывается как JSONP. Это более подробно описано на странице $.ajax() в описании параметра jsonp.

The jqXHR Object

Начиная с jQuery 1.5, все Ajax методы jQuery возвращают объект XMLHTTPRequest. Объект jQuery XHR или «jqXHR,» возвращается $.get() реализацией интерфейса Promise и предоставляет все его свойства, меоды и повередени Promise в целом (смотрите Deferred object для справки). Методы jqXHR.done() (успех), jqXHR.fail() (ошибка), and jqXHR.always() (для гарантированного обработчика, не зависимо от успеха или ошибки ответа, добавлен в версии jQuery 1.6) принимают функцию, которая вызывается когда запрос завершается. Аргументы этих функция описаны на странице jqXHR Object в разделе $.ajax() справки.

Интерфейс Promise также разрешает Ajax методам, включая $.get(), вызывать неоднократно по цепочке методы .done(), .fail() и .always() для одного запроса и даже назначать его обработчики, даже после того как запрос был завершен. Если запрос уже выполнен, то функция обратного вызова выполняется немедленно.

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 = $.getJSON( "example.json", function() {

console.log( "success" );

console.log( "second success" );

console.log( "complete" );

// Perform other work here ...

// Set another completion function for the request above

jqxhr.complete(function() {

console.log( "second complete" );

Уведомление об устаревании

Функции обратного вызова jqXHR.success(), jqXHR.error(), and jqXHR.complete() удалены в jQuery 3.0. Используйте методы jqXHR.done(), jqXHR.fail() и jqXHR.always() вместо них.

jQuery.getJSON()

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

Asynchronous HTTP (Ajax) JSON encoded load request.

Description

The jQuery.getJSON() Ajax method, allows us to load data from the server, that has been JSON encoded, using a HTTP GET request.

Shorthand version $.getJSON()

  • 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.getJSON() 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 Deferred object, the jqXHR object also provides .always(), .done() and
    .fail() methods. These methods take a function argument that is called when the jQuery.getJSON() request terminates and the function receives the same arguments as the same-named
    .complete().success() and .error() 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 .complete().success() and .error() callbacks are deprecated from use on request completion from jQuery 1.8. This is for completion
      processing only and the Ajax settings will still have these values. Best practice is to use .always(), .done() and .fail() methods on request completion to future proof code.
  • 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

Parameter Description
jQuery.getJSON( url [, data] [, function(data, textStatus, jqXHR)] ) Load data from the server, that has been JSON encoded, using a HTTP GET request.

Parameters

Parameter Description Type
url A string containing the URL to send the request to. String
data A map 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.
PlainObject
function(data, textStatus, jqXHR) A callback function executed when the request succeeds. Function

Return

A jqXHR object.

jQuery.getJSON( url [, data] [,function (data, textStatus, jqXHR)] ) Example
Ajax  <<  Top

Load data from the server, that has been JSON encoded, using a HTTP GET request.

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


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

In the example below when we press the button the first time we use the jQuery.getJSON() method with a url and a success handler. We interrogate the returned JSON data and move it to an array before appending it to our page.


$(function(){
  $('#btn5').one('click', function(){
    $.getJSON('../../pages/testfileb.html', function(data) {
      var sayingsList = [];

      $.each(data, function(key, val) {
        sayingsList.push('<li>' + val + '</li>');
      });

      $('<ul/>', {
          html: sayingsList.join('')
        }).appendTo('#div4');
      })
      .done(function() { $('#div4').append('getJSON request succeeded! </li>'); })
      .fail(function() { $('#div4').append('getJSON request failed! </li>'); })
      .always(function() { $('#div4').append('getJSON request ended! </li></li>'); 
    });
  });
});

/*
 * The external JSON file called from $.getJSON() (url: "../../pages/testfileb.html")
 * is shown below.
 */
{
  "1": "A stitch in time saves nine",
  "2": "The quick brown fox jumps over the lazy dog",
  "3": "10 green bottles",
  "4": "Blood is thicker than water",
  "5": "A bird in the hand is worth two in the bush",
  "6": "Prevention is better than cure",
  "7": "To be or not to be"
}

div4. Some initial text.

Related Tutorials

jQuery Advanced Tutorials — Lesson 9 — Ajax Shorthand Methods

Описание: загрузка данных в формате JSON с сервера с помощью HTTP-запроса GET.

Это сокращенная функция «Аякс»,которая эквивалентна:

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

Данные, отправляемые на сервер, добавляются к URL-адресу в виде строки запроса. Если значение параметра data представляет собой простой объект, оно преобразуется в строку и кодируется в URL-адресе перед добавлением к URL-адресу.

В большинстве реализаций будет указываться обработчик успеха:

$.getJSON( "ajax/test.json", function( data ) {
  var items = [];
  $.each( data, function( key, val ) {
    items.push( "<li id='" + key + "'>" + val + "</li>" );
  });
 
  $( "<ul/>", {
    "class": "my-new-list",
    html: items.join( "" )
  }).appendTo( "body" );
});

Этот пример,конечно,опирается на структуру JSON-файла:

{
  "one": "Singular sensation",
  "two": "Beady little eyes",
  "three": "Little birds pitch by my doorstep"
}

Используя эту структуру,пример циклически проходит через запрашиваемые данные,строит неупорядоченный список и добавляет его в тело.

success обратного вызова передается возвращенные данные, который обычно представляет собой объект JavaScript или массив , как это определено структурой JSON и анализируется с помощью $.parseJSON() метод. Также передается текстовый статус ответа.

Начиная с jQuery 1.5 , функция обратного вызова success получает объект «jqXHR» (в jQuery 1.4 он получил объект XMLHttpRequest ). Однако, поскольку JSONP и междоменные запросы GET не используютXHR, в этих случаях параметры jqXHR и textStatus , переданные в обратный вызов успеха, не определены.

Важно: Начиная с jQuery 1.4, если файл JSON содержит синтаксическую ошибку, запрос обычно не выполняется без уведомления. По этой причине избегайте частого редактирования данных JSON вручную. JSON — это формат обмена данными с более строгими правилами синтаксиса, чем в нотации литерала объекта JavaScript. Например, все строки, представленные в JSON, независимо от того, являются ли они свойствами или значениями, должны быть заключены в двойные кавычки. Подробнее о формате JSON см. Https://json.org/ .

JSONP

Если URL включает строку «callback =?» (или аналогичный, как определено серверным API), вместо этого запрос обрабатывается как JSONP. Подробнее см. Обсуждение типа данных jsonp в $.ajax() .

Объект jqXHR

Начиная с jQuery 1.5 , все методы Ajax jQuery возвращают расширенный набор объекта XMLHTTPRequest . Этот объект jQuery XHR или «jqXHR», возвращаемый $.getJSON() реализует интерфейс Promise, предоставляя ему все свойства, методы и поведение Promise (см. Отложенный объект для получения дополнительной информации). jqXHR.done() (для успеха), jqXHR.fail() (для ошибок) и jqXHR.always() (для завершения, будь то успех или ошибка; добавлено в JQuery 1.6) методы принимает аргумент функции, которая вызывается , когда запрос прекращается. Для получения информации об аргументах, которые получает эта функция, см. Раздел jqXHR Object в $.ajax() документация.

Интерфейс Promise в jQuery 1.5 также позволяет Ajax-методам jQuery, включая $.getJSON() , .done() несколько обратных вызовов .done () , .always() и .fail() по одному запросу и даже назначать эти обратные вызовы после запрос может быть выполнен. Если запрос уже завершен, обратный вызов запускается немедленно.


var jqxhr = $.getJSON( "example.json", function() {
  console.log( "success" );
})
  .done(function() {
    console.log( "second success" );
  })
  .fail(function() {
    console.log( "error" );
  })
  .always(function() {
    console.log( "complete" );
  });
 

 

jqxhr.always(function() {
  console.log( "second complete" );
});

Deprecation Notice

jqXHR.success() , jqXHR.error() , и jqXHR.complete() методы обратного удалены от JQuery 3.0 . jqXHR.done() вы можете использовать jqXHR.done () , jqXHR.fail() и jqXHR.always() .

Examples:

Загружает четыре последних снимка горы Rainier из JSONP API Flickr.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery.getJSON demo</title>
  <style>
  img {
    height: 100px;
    float: left;
  }
  </style>
  <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
 
<div id="images"></div>
 
<script>
(function() {
  var flickerAPI = "https://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
  $.getJSON( flickerAPI, {
    tags: "mount rainier",
    tagmode: "any",
    format: "json"
  })
    .done(function( data ) {
      $.each( data.items, function( i, item ) {
        $( "<img>" ).attr( "src", item.media.m ).appendTo( "#images" );
        if ( i === 3 ) {
          return false;
        }
      });
    });
})();
</script>
 
</body>
</html>

Demo:

Загрузите данные JSON из test.js и получите доступ к имени из возвращаемых данных JSON.

$.getJSON( "test.js", function( json ) {
  console.log( "JSON Data: " + json.users[ 3 ].name );
 });

Загрузите данные JSON из test.js,передав дополнительные данные,и получите доступ к имени из возвращаемых данных JSON.При возникновении ошибки зарегистрируйте вместо нее сообщение об ошибке.

$.getJSON( "test.js", { name: "John", time: "2pm" } )
  .done(function( json ) {
    console.log( "JSON Data: " + json.users[ 3 ].name );
  })
  .fail(function( jqxhr, textStatus, error ) {
    var err = textStatus + ", " + error;
    console.log( "Request Failed: " + err );
});

cpp

Функция $.getJSON() позволяет получить данные в форматах JSON и JSONP. Запрос отправляется методом GET. Формат функции:

<jqXHR> = $.getJSON(<URL>[, <Данные>][, <Функция обратного вызова>])

Необязательный параметр <Данные> позволяет указать строку с закодированными данными, которая будет добавлена к URL после символа вопроса (содержимое файла ajax.php см. в листинге 3.11):

$.getJSON('/ajax.php', 'txt1=1&txt2=2', function(json) {
   $('#div_ajax').html(json.txt1 + '<br>' + json.txt2);
});

Можно также передать несколько параметров в виде объекта. В этом случае параметры и значения должны быть указаны следующим образом:

{
   Параметр1: "Значение1",
   Параметр2: "Значение2",
   ...
   ПараметрN: "ЗначениеN"
}

Пример:

$.getJSON('/ajax.php', {txt1: '1', txt2: '2'}, function(json) {
   $('#div_ajax').html(json.txt1 + '<br>' + json.txt2);
});

В качестве параметра <Функция обратного вызова> указывается ссылка на функцию следующего формата:

function <Название функции>(<JSON-объект>[, <Статус>[, 
                            <Объект jqXHR>]]) {
   // ...
}

Функция будет вызвана после окончания загрузки в случае успешного результата. Внутри функции обратного вызова доступен указатель this на объект с параметрами запроса. Если в первом параметре указать переменную, то через нее будет доступен обработанный JSON-объект на основе данных, загруженных с сервера. Через параметр <Статус> доступен статус запроса (значение success — при успешном выполнении), а через параметр <Объект jqXHR> доступна ссылка на объект, имитирующий объект XMLHttpRequest.

Функция $.getJSON() возвращает ссылку на объект jqXHR. Обработать ошибку загрузки можно с помощью метода fail() объекта jqXHR:

$.getJSON('/ajax2.php', {txt1: '1', txt2: '2'}, function(json) {
   $('#div_ajax').html(json.txt1 + '<br>' + json.txt2);
}).fail( function( xhr, status, error ) {
   $('#div_ajax').text('Ошибка: ' + error);
});

Рассмотрим использование функции $.getJSON() на примере. Создадим документ с формой (листинг 3.20), который будет обмениваться данными с файлом ajax.php (см. листинг 3.11).

<!doctype html>
<html lang="ru">
<head>
   <meta charset="utf-8">
   <meta name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no">
   <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
   <title>Функция $.getJSON()</title>
</head>
<body>
<div class="container my-3">
  <form action="ajax.php" method="GET" onsubmit="return false;">
    <div class="form-group">
      <input type="text" class="form-control" id="txt1">
    </div>
    <div class="form-group">
      <input type="text" class="form-control" id="txt2">
    </div>
    <button type="button" class="btn btn-primary"
            id="btnSend">Отправить</button>
  </form>
</div>
<div class="container my-3">
   <div id="div_ajax"></div>
</div>

<script src="/js/jquery.min.js"></script>
<script>
$('#btnSend').click( function() {
   // Отправка запроса методом GET
   var txt1 = $('#txt1').val();
   var txt2 = $('#txt2').val();
   if (txt1 === '' || txt2 === '') {
      window.alert('Не заполнено поле');
      return;
   }
   $('#div_ajax').text('Загрузка...');
   $.getJSON('/ajax.php', { txt1: txt1, txt2: txt2 },
      function(json, status, xhr) {
         $('#div_ajax').html(json.txt1 + '<br>' + json.txt2);
         $('#txt1, #txt2').val('');
   }).fail( function( xhr, status, error ) {
      $('#div_ajax').text('Ошибка: ' + error);
   });
});
</script>
</body>
</html>

Функция $.getJSON() позволяет также получать данные в формате JSONP с другого домена. Чтобы отправить данные этим способом, необходимо после параметров в URL-адресе указать конструкцию:

Название параметра может быть произвольным:

http://site1/ajax.php?txt=test&callback=?

Если в конце запроса указан вопросительный знак, то данные будут отправлены не с помощью технологии AJAX, а путем создания тега <script> с указанием URL-адреса в параметре src. Вместо вопросительного знака будет вставлено произвольное значение. Запрос на сервер будет выглядеть примерно следующим образом:

http://site1/ajax.php?txt=test&callback=jQuery341041636825067330563_1590512642652&_=1590512642653

Как видно из результата, вместо знака вопроса мы получили следующую строку:

jQuery341041636825067330563_1590512642652&_=1590512642653

Значение параметра callback необходимо указать перед данными в виде объекта в скрипте на сервере. Сами данные указываются внутри круглых скобок. Это соответствует вызову функции и передаче объекта с данными в качестве параметра:

jQuery341041636825067330563_1590512642652({
   txt1: "Значение 1",
   txt2: "Значение 2"
});

В качестве примера рассмотрим получение данных в формате JSONP с другого домена. Создадим документ с формой http://localhost/test.html (листинг 3.21), который будет обмениваться данными с файлом http://site1/ajax.php (листинг 3.22).

<!doctype html>
<html lang="ru">
<head>
   <meta charset="utf-8">
   <meta name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no">
   <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
   <title>Функция $.getJSON() и JSONP</title>
</head>
<body>
<div class="container my-3">
  <form action="ajax.php" method="GET" onsubmit="return false;">
    <div class="form-group">
      <input type="text" class="form-control" id="txt1">
    </div>
    <div class="form-group">
      <input type="text" class="form-control" id="txt2">
    </div>
    <button type="button" class="btn btn-primary"
            id="btnSend">Отправить</button>
  </form>
</div>
<div class="container my-3">
   <div id="div_ajax"></div>
</div>

<script src="/js/jquery.min.js"></script>
<script>
$('#btnSend').click( function() {
   var txt1 = $('#txt1').val();
   var txt2 = $('#txt2').val();
   if (txt1 === '' || txt2 === '') {
      window.alert('Не заполнено поле');
      return;
   }
   $('#div_ajax').text('Загрузка...');
   var url = 'http://site1/ajax.php?txt1=' + encodeURIComponent(txt1);
   url += '&txt2=' + encodeURIComponent(txt2) + '&callback=?';
   $.getJSON(url, function(obj) {
      $('#div_ajax').html(obj.txt1 + '<br>' + obj.txt2);
      $('#txt1, #txt2').val('');
   }).fail( function(xhr, status, error) {
      $('#div_ajax').text('Ошибка: ' + error);
   });
});
</script>
</body>
</html>
<?php
// Указываем MIME-тип и кодировку
header('Content-Type: text/javascript; charset=utf-8');
if ( !isset($_GET['callback']) || !isset($_GET['txt1']) || 
     !isset($_GET['txt2']) ) {
   exit('Некорректные параметры запроса');
}
$txt1 = addslashes($_GET['txt1']);
$txt2 = addslashes($_GET['txt2']);
echo $_GET['callback']; ?>({
   txt1: "<?=$txt1?>",
   txt2: "<?=$txt2?>"
});

Учебник по jQuery и AJAX
Учебник по jQuery и AJAX в формате PDF

Понравилась статья? Поделить с друзьями:
  • Getcontact изменить номер телефона как
  • Getcommmodemstatus function failed win error code 6 mr140diag
  • Getch c ошибка
  • Get ошибка 400
  • Get validation error django