LEARNING JAVASCRIPT - Trang 304

Ajax

jQuery provides convenience methods that make Ajax calls easier. jQuery exposes an

ajax

method that allows sophisticated control over an Ajax call. It also provides con‐

venience methods,

get

and

post

, that perform the most common types of Ajax calls.

While these methods support callbacks, they also return promises, which is the rec‐

ommended way to handle the server response. For example, we can use

get

to rewrite

our

refreshServerInfo

example from before:

function

refreshServerInfo

() {

const

$serverInfo

=

$

(

'.serverInfo'

);

$

.

get

(

'http://localhost:7070'

).

then

(

// successful return

function

(

data

) {

Object

.

keys

(

data

).

forEach

(

p

=>

{

$(

`[data-replace="

${

p

}

"]`

).

text

(

data

[

p

]);

});
},

function

(

jqXHR

,

textStatus

,

err

) {

console

.

error

(

err

);

$serverInfo

.

addClass

(

'error'

)

.

html

(

'Error connecting to server.'

);

}
);
}

As you can see, we have significantly simplified our Ajax code by using jQuery.

Conclusion

The future of jQuery is unclear. Will improvements to JavaScript and browser APIs

render jQuery obsolete? Will the “vanilla JavaScript” purists be vindicated? Only time

will tell. I feel that jQuery remains useful and relevant, and will so for the foreseeable

future. Certainly the usage of jQuery remains quite high, and any aspiring developer

would do well to at least understand the basics.
If you want to learn more about jQuery, I recommend

jQuery: Novice to Ninja

by

Earle Castledine and Craig Sharkie. The online

jQuery documentation

is also quite

good.

280 | Chapter 19: jQuery

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.