Skip to content
Browse files

Code and prose style improvements to all articles in Ajax chapter. Fi…

…xes #283.
  • Loading branch information...
1 parent 7320dd6 commit 64b6981ee531714bbe4d1cfc6d24a8df6a299222 @alimony alimony committed with ajpiano Mar 14, 2013
Showing with 163 additions and 216 deletions.
  1. +5 −5 page/ajax.md
  2. +37 −59 page/ajax/ajax-and-forms.md
  3. +9 −14 page/ajax/ajax-events.md
  4. +70 −87 page/ajax/jquery-ajax-methods.md
  5. +25 −30 page/ajax/key-concepts.md
  6. +17 −21 page/ajax/working-with-jsonp.md
View
10 page/ajax.md
@@ -7,14 +7,14 @@ customFields:
value: "refresh"
---
-Traditionally webpages required reloading to update their content. For web-based email this meant that users had to manually reload their inbox to check and see if they had new mail. This had huge drawbacks: it was slow and it required user input. When the user reloaded their inbox, the server had to reconstruct the entire web page and resend all of the HTML, CSS, JavaScript, as well as the user's email. This was hugely inefficient. Ideally, the server should only have to send the user's new messages, not the entire page. By 2003 all the major browsers, solved this issue by adopting the XMLHttpRequest (XHR) object, allowing browsers to communicate with the server without requiring a page reload.
+Traditionally webpages required reloading to update their content. For web-based email this meant that users had to manually reload their inbox to check and see if they had new mail. This had huge drawbacks: it was slow and it required user input. When the user reloaded their inbox, the server had to reconstruct the entire web page and resend all of the HTML, CSS, JavaScript, as well as the user's email. This was hugely inefficient. Ideally, the server should only have to send the user's new messages, not the entire page. By 2003, all the major browsers solved this issue by adopting the XMLHttpRequest (XHR) object, allowing browsers to communicate with the server without requiring a page reload.
-The XMLHttpRequest object is part of a technology called Ajax (Asynchronous JavaScript and XML). Using Ajax, data could then be passed between the browser and the server, using the XMLHttpRequest API, without having to reload the web page. With the widespread adoption of the XMLHttpRequest object it quickly became possible to build web applications like Google Maps, and GMail that used XMLHttpRequest to get new map tiles, or new email without having to reload the entire page.
+The XMLHttpRequest object is part of a technology called Ajax (Asynchronous JavaScript and XML). Using Ajax, data could then be passed between the browser and the server, using the XMLHttpRequest API, without having to reload the web page. With the widespread adoption of the XMLHttpRequest object it quickly became possible to build web applications like Google Maps, and Gmail that used XMLHttpRequest to get new map tiles, or new email without having to reload the entire page.
-Ajax requests are triggered by JavaScript code; your code sends a request to a URL, and when it receives a response, a callback function can be triggered to handle the response. Because the request is asynchronous, the rest of your code continues to execute while the request is being processed, so its imperative that a callback be used to handle the response.
+Ajax requests are triggered by JavaScript code; your code sends a request to a URL, and when it receives a response, a callback function can be triggered to handle the response. Because the request is asynchronous, the rest of your code continues to execute while the request is being processed, so it's imperative that a callback be used to handle the response.
Unfortunately, different browsers implement the Ajax API differently. Typically this meant that developers would have to account for all the different browsers to ensure that Ajax would work universally. Fortunately, jQuery provides Ajax support that abstracts away painful browser differences. It offers both a full-featured `$.ajax()` method, and simple convenience methods such as `$.get()`, `$.getScript()`, `$.getJSON()`, `$.post()`, and `$().load()`.
-Most jQuery applications dont in fact use XML, despite the name Ajax; instead, they transport data as plain HTML or JSON (JavaScript Object Notation).
+Most jQuery applications don't in fact use XML, despite the name "Ajax"; instead, they transport data as plain HTML or JSON (JavaScript Object Notation).
-In general, Ajax does not work across domains. For instance, a webpage loaded from example1.com is unable to make an Ajax request to example2.com as it would violate the same origin policy. As a work around, JSONP (JSON with Padding) uses `<script>` tags to load files containing arbitrary JavaScript content and JSON, from another domain. More recently browsers have implemented a technology called Cross-origin resource sharing (CORS), that allows Ajax requests to different domains.
+In general, Ajax does not work across domains. For instance, a webpage loaded from example1.com is unable to make an Ajax request to example2.com as it would violate the same origin policy. As a work around, JSONP (JSON with Padding) uses `<script>` tags to load files containing arbitrary JavaScript content and JSON, from another domain. More recently browsers have implemented a technology called Cross-Origin Resource Sharing (CORS), that allows Ajax requests to different domains.
View
96 page/ajax/ajax-and-forms.md
@@ -2,20 +2,20 @@
title: Ajax and Forms
level: beginner
source: http://jqfundamentals.com/legacy
-attribution:
+attribution:
- jQuery Fundamentals
---
-jQuerys ajax capabilities can be especially useful when dealing with forms. There are several advantages, which can range from serialization, to simple client-side validation (e.g. "Sorry, that username is taken"), to [prefilters](http://api.jquery.com/extending-ajax/#Prefilters) (explained below), and even more!
+jQuery's ajax capabilities can be especially useful when dealing with forms. There are several advantages, which can range from serialization, to simple client-side validation (e.g. "Sorry, that username is taken"), to [prefilters](http://api.jquery.com/extending-ajax/#Prefilters) (explained below), and even more!
### Serialization
-Serializing form inputs in jQuery is extremely easy. Two methods come supported natively - `$.fn.serialize` and `$.fn.serializeArray`. While the names are fairly self-explanatory, there are many advantages to using them.
+Serializing form inputs in jQuery is extremely easy. Two methods come supported natively `$.fn.serialize` and `$.fn.serializeArray`. While the names are fairly self-explanatory, there are many advantages to using them.
The `serialize` method serializes a form's data into a query string. For the element's value to be serialized, it **must** have a `name` attribute. Please note that values from inputs with a type of `checkbox` or `radio` are included only if they are checked.
```
// Turning form data into a query string
-$("#myForm").serialize();
+$( "#myForm" ).serialize();
// creates a query string like this:
// field_1=something&field2=somethingElse
@@ -25,108 +25,86 @@ While plain old serialization is great, sometimes your application would work be
```
// Creating an array of objects containing form data
-$("#myForm").serializeArray();
+$( "#myForm" ).serializeArray();
// creates a structure like this:
// [
// {
-//
// name : "field_1",
// value : "something"
-//
// },
// {
-//
// name : "field_2",
// value : "somethingElse"
-//
// }
// ]
```
### Client-side validation
-Client-side validation is, much like many other things, extremely easy using jQuery. While there are several cases developers can test for, some of the most common ones are: presence of a required input, valid usernames/emails/phone numbers/etc..., or checking an "I agree..." box.
+Client-side validation is, much like many other things, extremely easy using jQuery. While there are several cases developers can test for, some of the most common ones are: presence of a required input, valid usernames/emails/phone numbers/etc&hellip;, or checking an "I agree&hellip;" box.
Please note that it is advisable that you also perform server-side validation for your inputs. However, it typically makes for a better user experience to be able to validate some things without submitting the form.
With that being said, let's jump on in to some examples! First, we'll see how easy it is to check if a required field doesn't have anything in it. If it doesn't, then we'll `return false`, and prevent the form from processing.
```
// Using validation to check for the presence of an input
-$("#form").submit(function( event ) {
-
- // if .required's value's length is zero
- if ( $(".required").val().length === 0 ) {
-
- // usually show some kind of error message here
-
- // this prevents the form from submitting
- return false;
-
- } else {
-
- // run $.ajax here
-
- }
-
+$( "#form" ).submit(function( event ) {
+ // if .required's value's length is zero
+ if ( $( ".required" ).val().length === 0 ) {
+ // usually show some kind of error message here
+
+ // this prevents the form from submitting
+ return false;
+ } else {
+ // run $.ajax here
+ }
});
```
-Let's see how easy it is to check for invalid characters in a username:
+Let's see how easy it is to check for invalid characters in a phone number:
```
// Validate a phone number field
-$("#form").submit(function( event ) {
-
- var inputtedPhoneNumber = $("#phone").val();
- // match only numbers
- var phoneNumberRegex = ^\d*$/;
-
- // if the phone number doesn't match the regex
- if ( !phoneNumberRegex.test( inputtedPhoneNumber ) ) {
-
- // usually show some kind of error message here
+$( "#form" ).submit(function( event ) {
+ var inputtedPhoneNumber = $( "#phone" ).val();
- // prevent the form from submitting
- return false;
+ // match only numbers
+ var phoneNumberRegex = /^\d*$/;
- } else {
-
- // run $.ajax here
-
- }
+ // if the phone number doesn't match the regex
+ if ( !phoneNumberRegex.test( inputtedPhoneNumber ) ) {
+ // usually show some kind of error message here
+ // prevent the form from submitting
+ return false;
+ } else {
+ // run $.ajax here
+ }
});
```
### Prefiltering
A prefilter is a way to modify the ajax options before each request is sent (hence, the name `prefilter`).
-For example, say we would like to modify all crossDomain requests through a proxy. To do so with a prefilter is quite simple:
+For example, say we would like to modify all cross-domain requests through a proxy. To do so with a prefilter is quite simple:
```
// Using a proxy with a prefilter
$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
-
- if ( options.crossDomain ) {
-
- options.url = "http://mydomain.net/proxy/" + encodeURIComponent( options.url );
-
- options.crossDomain = false;
-
- }
-
+ if ( options.crossDomain ) {
+ options.url = "http://mydomain.net/proxy/" + encodeURIComponent( options.url );
+ options.crossDomain = false;
+ }
});
```
You can pass in an optional argument before the callback function that specifies which `dataTypes` you'd like the prefilter to be applied to. For example, if we want our prefilter to only apply to `JSON` and `script` requests, we'd do:
```
-// Using the optional dataTypes argument">
+// Using the optional dataTypes argument
$.ajaxPrefilter( "json script", function( options, originalOptions, jqXHR ) {
-
- // do all of the prefiltering here, but only for
- // requests that indicate a dataType of "JSON" or "script"
-
+ // do all of the prefiltering here, but only for
+ // requests that indicate a dataType of "JSON" or "script"
});
```
View
23 page/ajax/ajax-events.md
@@ -2,25 +2,20 @@
title : Ajax Events
level: beginner
source: http://jqfundamentals.com/legacy
-attribution:
+attribution:
- jQuery Fundamentals
---
-Often, youll want to perform an operation whenever an Ajax requests starts or
-stops, such as showing or hiding a loading indicator. Rather than defining
+Often, you'll want to perform an operation whenever an Ajax requests starts or
+stops, such as showing or hiding a loading indicator. Rather than defining
this behavior inside every Ajax request, you can bind Ajax events to elements
-just like you'd bind other events. For a complete list of Ajax events, visit
-[ Ajax Events documentation on docs.jquery.com ]( http://docs.jquery.com/Ajax_Events ).
+just like you'd bind other events. For a complete list of Ajax events, visit
+[Ajax Events documentation on docs.jquery.com](http://docs.jquery.com/Ajax_Events).
```
// Setting up a loading indicator using Ajax Events
-$("#loading_indicator").ajaxStart(function() {
-
- $( this ).show();
-
- }).ajaxStop(function() {
-
- $( this ).hide();
-
+$( "#loading_indicator" ).ajaxStart(function() {
+ $( this ).show();
+}).ajaxStop(function() {
+ $( this ).hide();
});
-
```
View
157 page/ajax/jquery-ajax-methods.md
@@ -2,86 +2,79 @@
title : jQuery's Ajax-Related Methods
level: beginner
source: http://jqfundamentals.com/legacy
-attribution:
+attribution:
- jQuery Fundamentals
---
While jQuery does offer many Ajax-related convenience methods, the core
`$.ajax` method is at the heart of all of them, and understanding it is
-imperative. We'll review it first, and then touch briefly on the convenience
+imperative. We'll review it first, and then touch briefly on the convenience
methods.
-I generally use the `$.ajax` method and do not use convenience methods. As
+I generally use the `$.ajax` method and do not use convenience methods. As
you'll see, it offers features that the convenience methods do not, and its
syntax is more easily understandable, in my opinion.
### `$.ajax`
-jQuerys core `$.ajax` method is a powerful and straightforward way of creating
-Ajax requests. It takes a configuration object that contains all the
-instructions jQuery requires to complete the request. The `$.ajax` method is
+jQuery's core `$.ajax` method is a powerful and straightforward way of creating
+Ajax requests. It takes a configuration object that contains all the
+instructions jQuery requires to complete the request. The `$.ajax` method is
particularly valuable because it offers the ability to specify both success and
-failure callbacks. Also, its ability to take a configuration object that can
-be defined separately makes it easier to write reusable code. For complete
+failure callbacks. Also, its ability to take a configuration object that can
+be defined separately makes it easier to write reusable code. For complete
documentation of the configuration options, visit
[http://api.jquery.com/jQuery.ajax/](http://api.jquery.com/jQuery.ajax/ "$.ajax
documentation on api.jquery.com").
```
// Using the core $.ajax method
$.ajax({
-
- // the URL for the request
- url : "post.php",
-
- // the data to send
- // (will be converted to a query string)
- data : {
- id : 123
- },
-
- // whether this is a POST or GET request
- type : "GET",
-
- // the type of data we expect back
- dataType : "json",
-
- // code to run if the request succeeds;
- // the response is passed to the function
- success : function( json ) {
- $("<h1/>").text( json.title ).appendTo("body");
- $("<div class=\"content\"/>").html( json.html ).appendTo("body");
- },
-
- // code to run if the request fails;
- // the raw request and status codes are
- // passed to the function
- error : function( xhr, status ) {
- alert("Sorry, there was a problem!");
- },
-
- // code to run regardless of success or failure
- complete : function( xhr, status ) {
- alert("The request is complete!");
- }
-
+ // the URL for the request
+ url: "post.php",
+
+ // the data to send (will be converted to a query string)
+ data: {
+ id: 123
+ },
+
+ // whether this is a POST or GET request
+ type: "GET",
+
+ // the type of data we expect back
+ dataType : "json",
+
+ // code to run if the request succeeds;
+ // the response is passed to the function
+ success: function( json ) {
+ $( "<h1/>" ).text( json.title ).appendTo( "body" );
+ $( "<div class=\"content\"/>").html( json.html ).appendTo( "body" );
+ },
+
+ // code to run if the request fails; the raw request and
+ // status codes are passed to the function
+ error: function( xhr, status ) {
+ alert( "Sorry, there was a problem!" );
+ },
+
+ // code to run regardless of success or failure
+ complete: function( xhr, status ) {
+ alert( "The request is complete!" );
+ }
});
```
-<div class="note" >
-### Note
-
-A note about the dataType setting: if the server sends back data that is in a
+**Note:** A note about the `dataType` setting: if the server sends back data that is in a
different format than you specify, your code may fail, and the reason will not
-always be clear, because the HTTP response code will not show an error. When
+always be clear, because the HTTP response code will not show an error. When
working with Ajax requests, make sure your server is sending back the data type
-you're asking for, and verify that the Content-type header is accurate for the
-data type. For example, for JSON data, the Content-type header should be
-`application/json`. </div>
+you're asking for, and verify that the `Content-type` header is accurate for the
+data type. For example, for JSON data, the `Content-type` header should be
+`application/json`.
### `$.ajax` Options
There are many, many options for the `$.ajax` method, which is part of its
-power. For a complete list of options, visit
+power. For a complete list of options, visit
[http://api.jquery.com/jQuery.ajax/](http://api.jquery.com/jQuery.ajax/ "$.ajax
documentation on api.jquery.com"); here are several that you will use
frequently:
@@ -94,8 +87,8 @@ of other code until the response is received.
#### cache
-Whether to use a cached response if available. Defaults to true for all
-dataTypes except "script" and "jsonp". When set to false, the URL will simply
+Whether to use a cached response if available. Defaults to `true` for all
+`dataType`s except "script" and "jsonp". When set to `false`, the URL will simply
have a cachebusting parameter appended to it.
#### complete
@@ -118,7 +111,7 @@ string, such as `foo=bar&amp;baz=bim`.
#### dataType
The type of data you expect back from the server. By default, jQuery will look
-at the MIME type of the response if no dataType is specified.
+at the MIME type of the response if no `dataType` is specified.
#### error
@@ -133,7 +126,7 @@ Defaults to "callback".
#### success
A callback function to run if the request succeeds. The function receives the
-response data (converted to a JavaScript object if the dataType was JSON), as
+response data (converted to a JavaScript object if the `dataType` was JSON), as
well as the text status of the request and the raw request object.
#### timeout
@@ -142,7 +135,7 @@ The time in milliseconds to wait before considering the request a failure.
#### traditional
-Set to true to use the param serialization style in use prior to jQuery 1.4.
+Set to `true` to use the param serialization style in use prior to jQuery 1.4.
For details, see
[http://api.jquery.com/jQuery.param/](http://api.jquery.com/jQuery.param/
"$.param documentation on api.jquery.com").
@@ -159,13 +152,13 @@ The URL for the request.
The `url` option is the only required property of the `$.ajax` configuration
object; all other properties are optional. This can also be passed as the first
-argument to $.ajax, and the options object as the second argument.
+argument to `$.ajax`, and the options object as the second argument.
### Convenience Methods
If you don't need the extensive configurability of `$.ajax`, and you don't care
about handling errors, the Ajax convenience functions provided by jQuery can be
-useful, terse ways to accomplish Ajax requests. These methods are just
+useful, terse ways to accomplish Ajax requests. These methods are just
"wrappers" around the core `$.ajax` method, and simply pre-set some of the
options on the `$.ajax` method.
@@ -198,11 +191,7 @@ The URL for the request. Required.
The data to be sent to the server. Optional. This can either be an object or a
query string, such as `foo=bar&amp;baz=bim`.
-<div class="note">
-### Note
-
-This option is not valid for `$.getScript`.
-</div>
+**Note:** This option is not valid for `$.getScript`.
#### success callback
@@ -215,55 +204,49 @@ object.
The type of data you expect back from the server. Optional.
-<div class="note">
-### Note
-
-This option is only applicable for methods that don't already specify the data
-type in their name. </div>
+**Note:** This option is only applicable for methods that don't already specify the data
+type in their name.
```
// Using jQuery's Ajax convenience methods
-// get plain text or html
+
+// get plain text or HTML
$.get( "/users.php", {
- userId : 1234
+ userId: 1234
}, function( resp ) {
- console.log( resp ); // server response
+ console.log( resp ); // server response
});
// add a script to the page, then run a function defined in it
$.getScript( "/static/js/myScript.js", function() {
-
- functionFromMyScript();
-
+ functionFromMyScript();
});
// get JSON-formatted data from the server
$.getJSON( "/details.php", function( resp ) {
-
- // log each key in the response data
- $.each( resp, function( key, value ) {
- console.log( key + " : " + value );
- });
-
+ // log each key in the response data
+ $.each( resp, function( key, value ) {
+ console.log( key + " : " + value );
+ });
});
```
### `$.fn.load`
-The `$.fn.load` method is unique among jQuerys Ajax methods in that it is
-called on a selection. The `$.fn.load` method fetches HTML from a URL, and
-uses the returned HTML to populate the selected element(s). In addition to
+The `$.fn.load` method is unique among jQuery's Ajax methods in that it is
+called on a selection. The `$.fn.load` method fetches HTML from a URL, and
+uses the returned HTML to populate the selected element(s). In addition to
providing a URL to the method, you can optionally provide a selector; jQuery
will fetch only the matching content from the returned HTML.
```
// Using $.fn.load to populate an element
-$("#newContent").load("/foo.html");
+$( "#newContent" ).load( "/foo.html" );
```
```
// Using $.fn.load to populate an element based on a selector
-$("#newContent").load( "/foo.html #myDiv h1:first:", function( html ) {
- alert("Content updated!"");
+$( "#newContent" ).load( "/foo.html #myDiv h1:first:", function( html ) {
+ alert( "Content updated!" );
});
```
55 page/ajax/key-concepts.md
@@ -2,27 +2,27 @@
title : Key Concepts
level: beginner
source: http://jqfundamentals.com/legacy
-attribution:
+attribution:
- jQuery Fundamentals
---
Proper use of Ajax-related jQuery methods requires understanding some key
concepts first.
-### GET vs. Post
+### GET vs. POST
-The two most common methods for sending a request to a server are GET and
-POST. It’s important to understand the proper application of each.
+The two most common "methods" for sending a request to a server are GET and
+POST. It's important to understand the proper application of each.
The GET method should be used for non-destructive operations — that is,
-operations where you are only getting data from the server, not changing data
-on the server. For example, a query to a search service might be a GET
-request. GET requests may be cached by the browser, which can lead to
-unpredictable behavior if you are not expecting it. GET requests generally
+operations where you are only "getting" data from the server, not changing data
+on the server. For example, a query to a search service might be a GET
+request. GET requests may be cached by the browser, which can lead to
+unpredictable behavior if you are not expecting it. GET requests generally
send all of their data in a query string.
The POST method should be used for destructive operations — that is, operations
-where you are changing data on the server. For example, a user saving a blog
-post should be a POST request. POST requests are generally not cached by the
+where you are changing data on the server. For example, a user saving a blog
+post should be a POST request. POST requests are generally not cached by the
browser; a query string can be part of the URL, but the data tends to be sent
separately as post data.
@@ -35,55 +35,50 @@ object. There are several options:
#### text
-For transporting simple strings
+For transporting simple strings.
#### html
-For transporting blocks of HTML to be placed on the page
+For transporting blocks of HTML to be placed on the page.
#### script
-For adding a new script to the page
+For adding a new script to the page.
#### json
-For transporting JSON-formatted data, which can include strings, arrays, and objects
+For transporting JSON-formatted data, which can include strings, arrays, and objects.
-<div class="note">
-### Note
-
-As of jQuery 1.4, if the JSON data sent by your server isn't properly
-formatted, the request may fail silently. See
+**Note:** As of jQuery 1.4, if the JSON data sent by your server isn't properly
+formatted, the request may fail silently. See
[http://json.org](http://json.org) for details on properly formatting JSON, but
as a general rule, use built-in language methods for generating JSON on the
server to avoid syntax issues.
#### jsonp
-For transporting JSON data from another domain
+For transporting JSON data from another domain.
#### xml
-For transporting data in a custom XML schema
+For transporting data in a custom XML schema.
I am a strong proponent of using the JSON format in most cases, as it provides
the most flexibility. It is especially useful for sending both HTML and data at
the same time.
### A is for Asynchronous
-The asynchronicity of Ajax catches many new jQuery users off guard. Because
+The asynchronicity of Ajax catches many new jQuery users off guard. Because
Ajax calls are asynchronous by default, the response is not immediately
-available. Responses can only be handled using a callback. So, for example,
+available. Responses can only be handled using a callback. So, for example,
the following code will not work:
```
var response;
$.get( "foo.php", function( r ) {
-
- response = r;
-
+ response = r;
});
console.log( response ); // undefined
@@ -95,14 +90,14 @@ returned, if any.
```
$.get( "foo.php", function( response ) {
- console.log( response ); // server response
+ console.log( response ); // server response
});
```
### Same-Origin Policy and JSONP
In general, Ajax requests are limited to the same protocol (http or https), the
-same port, and the same domain as the page making the request. This limitation
+same port, and the same domain as the page making the request. This limitation
does not apply to scripts that are loaded via jQuery's Ajax methods.
The other exception is requests targeted at a JSONP service on another domain.
@@ -114,9 +109,9 @@ data you requested, wrapped in a callback function you provide.
### Ajax and Firebug
Firebug (or the Webkit Inspector in Chrome or Safari) is an invaluable tool for
-working with Ajax requests. You can see Ajax requests as they happen in the
+working with Ajax requests. You can see Ajax requests as they happen in the
Console tab of Firebug (and in the Resources > XHR panel of Webkit Inspector),
and you can click on a request to expand it and see details such as the request
-headers, response headers, response content, and more. If something isn't
+headers, response headers, response content, and more. If something isn't
going as expected with an Ajax request, this is the first place to look to
track down what's wrong.
View
38 page/ajax/working-with-jsonp.md
@@ -2,45 +2,41 @@
title : Working with JSONP
level: beginner
source: http://jqfundamentals.com/legacy
-attribution:
+attribution:
- jQuery Fundamentals
---
The advent of JSONP — essentially a consensual cross-site scripting hack — has
-opened the door to powerful mashups of content. Many prominent sites provide
-JSONP services, allowing you access to their content via a predefined API. A
+opened the door to powerful mashups of content. Many prominent sites provide
+JSONP services, allowing you access to their content via a predefined API. A
particularly great source of JSONP-formatted data is the [Yahoo! Query
Language](http://developer.yahoo.com/yql/console/), which we'll use in the
following example to fetch news about cats.
```
// Using YQL and JSONP
$.ajax({
+ url: "http://query.yahooapis.com/v1/public/yql",
- url : "http://query.yahooapis.com/v1/public/yql",
+ // the name of the callback parameter, as specified by the YQL service
+ jsonp: "callback",
- // the name of the callback parameter,
- // as specified by the YQL service
- jsonp : "callback",
+ // tell jQuery we're expecting JSONP
+ dataType: "jsonp",
- // tell jQuery we're expecting JSONP
- dataType : "jsonp",
-
- // tell YQL what we want and that we want JSON
- data : {
- q : "select title,abstract,url from search.news where query=\"cat\"",
- format : "json"
- },
-
- // work with the response
- success : function( response ) {
- console.log( response ); // server response
- }
+ // tell YQL what we want and that we want JSON
+ data: {
+ q: "select title,abstract,url from search.news where query=\"cat\"",
+ format: "json"
+ },
+ // work with the response
+ success: function( response ) {
+ console.log( response ); // server response
+ }
});
```
jQuery handles all the complex aspects of JSONP behind-the-scenes — all we have
to do is tell jQuery the name of the JSONP callback parameter specified by YQL
("callback" in this case), and otherwise the whole process looks and feels like
a normal Ajax request.
-

0 comments on commit 64b6981

Please sign in to comment.
Something went wrong with that request. Please try again.