I am developing asp.net mvc application, Java script will call controller for every 3 seconds and it should return list of json objects.I need to show the list of objects in table.Here, I am getting [object Object].should we deserialize that objects,if yes,then how to deserialize them.
Below is my java script code
<script>
var fun = set_Interval(my_Timer, 3000);
function my_Timer() {
$.ajax({
url: '@Url.Action("FirstAjax", "Home")',
//data: '{param : "value"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(response) {
alert(response);
}
function errorFunc() {
alert('error');
}
}
</script>
below is controller
public JsonResult FirstAjax()
{
var listt = AlgoLegsClass.DataGridAlgos;
JavaScriptSerializer js = new JavaScriptSerializer();
string ss = js.Serialize(listt);
return Json(ss, JsonRequestBehavior.AllowGet);
}
Output- After every 3 seconds the timer call the controller and it returns list of objects.In alert box it is displaying like "Parameter name":"Value".How can i get these values as i need to append this list to table
To Deserialize a JSON into a JavaScript object, here we will use a common method JSON. parse() method. JavaScript Object Notation is used to exchange data to or from a web server or RESTFull API. The data received from a web server is always a string.
parse() JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON. parse() , as the Javascript standard specifies.
The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
Since you specified dataType: "json"
in your ajax options, jQuery will already have done the deserialising of the JSON string back into a JavaScript object for you automatically.
What you're seeing is just what alert()
does with JavaScript objects/arrays by default when trying to make them visual as text.
Try
alert(JSON.stringify(response));
instead. This will print a version of your object which is serialised back to a JSON string and thus make it more human-readable.
Or you can just look in the Response section of the ajax call's entry in your Network tab (in the browser's Developer Tools).
Also if you're using a JsonResult (i.e. return Json...
) you do not need to serialise the object beforehand - MVC will do it for you. So chances are you're getting double-serialised nonsense.
Simply
return Json(listt, JsonRequestBehavior.AllowGet);
should work no problem.
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