Why code below sent data as City=Moscow&Age=25
instead of JSON format?
var arr = {City:'Moscow', Age:25}; $.ajax( { url: "Ajax.ashx", type: "POST", data: arr, dataType: 'json', async: false, success: function(msg) { alert(msg); } } );
The jQuery code uses getJSON() method to fetch the data from the file's location using an AJAX HTTP GET request. It takes two arguments. One is the location of the JSON file and the other is the function containing the JSON data. The each() function is used to iterate through all the objects in the array.
Create target "JSON object Mapper" object class file according to the business requirements. Create a "Controllers\HomeController. cs" file with default Index method and GetData(...) method with string type input query parameters for Ajax call with following lines of code i.e.
Because you haven't specified neither request content type, nor correct JSON request. Here's the correct way to send a JSON request:
var arr = { City: 'Moscow', Age: 25 }; $.ajax({ url: 'Ajax.ashx', type: 'POST', data: JSON.stringify(arr), contentType: 'application/json; charset=utf-8', dataType: 'json', async: false, success: function(msg) { alert(msg); } });
Things to notice:
JSON.stringify
method to convert a javascript object into a JSON string which is native and built-into modern browsers. If you want to support older browsers you might need to include json2.js contentType
property in order to indicate to the server the intent of sending a JSON requestdataType: 'json'
property is used for the response type you expect from the server. jQuery is intelligent enough to guess it from the server Content-Type
response header. So if you have a web server which respects more or less the HTTP protocol and responds with Content-Type: application/json
to your request jQuery will automatically parse the response into a javascript object into the success
callback so that you don't need to specify the dataType
property.Things to be careful about:
arr
is not an array. It is a javascript object with properties (City
and Age
). Arrays are denoted with []
in javascript. For example [{ City: 'Moscow', Age: 25 }, { City: 'Paris', Age: 30 }]
is an array of 2 objects.Because by default jQuery serializes objects passed as the data
parameter to $.ajax
. It uses $.param
to convert the data to a query string.
From the jQuery docs for $.ajax
:
[the
data
argument] is converted to a query string, if not already a string
If you want to send JSON, you'll have to encode it yourself:
data: JSON.stringify(arr);
Note that JSON.stringify
is only present in modern browsers. For legacy support, look into json2.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With