What is the difference between JSON and AJAX with jQuery?
The dataType
option simply changes what type of data jquery should expect from the server. It can be json
, jsonp
, html
, text
, xml
, or any custom datatype that you define a converter for. They all work in all browsers.
By default jQuery will try to detect what type of data is being returned if you do not supply a dataType
option, however I find that it doesn't automatically detect very well.
Edit:
but what if i need to return an object? is basically the answer of a database consult... is it better to use json or only jquery?
You can return an object in the form of html
, xml
, json
, or jsonp
. As long as it is in one of those formats, jQuery will be able to interpret it.
I think you are confusing the terms.
AJAX stands for Asynchronous Javascript and XML, which is a mechanism used to launch asynchronous HTTP requests to a server using JavaScript. Don't let the name fool you; there's no restriction on you only retrieving JavaScript or XML from this technique. You can quite happily return other data formats as well (HTML, plain text and JSON, to list a few).
JSON is just one of these formats. It's a data interchange format, where-as AJAX is a technique to communicate with a server after the initate page load has completed.
To answer your question on whether you need to specify the dataType
; jQuery will best guess the response format (be it HTML or JSON etc), so you're usually fine to omit it.