Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how does jquery guess the better datatype in Ajax method?

Tags:

jquery

it is wriiten in jquery document about Ajax method and its dataType:

' Default: Intelligent Guess '

how does jquery guess the better datatype for this method if nothing is selected for it?

if the output of requested url via ajax has html and script both,which one will be consider? html or script as dataType?

like image 393
hd. Avatar asked Apr 26 '11 08:04

hd.


People also ask

What is dataType in jQuery AJAX?

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.

How does AJAX work in jQuery?

jQuery provides several methods for AJAX functionality. With the jQuery AJAX methods, you can request text, HTML, XML, or JSON from a remote server using both HTTP Get and HTTP Post - And you can load the external data directly into the selected HTML elements of your web page!

Can you explain the difference between jQuery get () and jQuery AJAX ()?

get() method, which is a kind of shorthand for jQuery. ajax(). When using jQuery. get(), instead of passing in an object, you pass in arguments.


2 Answers

Primarily by looking at the Content-Type header of the response. Details in the ajaxHandleResponses function in the source (currently, for v1.5.2, starting at line 6,932).

From the documentation:

dataType: ... If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

Re

if the output of requested url via ajax has html and script both,which one will be consider? html or script as dataType?

That would be HTML with embedded script tags, which are also HTML. The script tags will be evaluated when (if) you insert the HTML into the DOM. Example: http://jsbin.com/utuha3

like image 90
T.J. Crowder Avatar answered Oct 27 '22 00:10

T.J. Crowder


Don't rely on jQuery to correctly guess your returned dataType. I was returning text but I was foolishly assuming that text was the default setting without looking at the documentation and my ajax requests would seemingly randomly fail, giving some of my users a bad experience and others would be fine.

i.e. jQuery cannot reliably intelligently guess text as a dataType.

like image 24
Bob Saget Avatar answered Oct 27 '22 01:10

Bob Saget