So I’ve been trying to read this object that was read from ajax get request but it’s not working, and I don’t know why… can anyone help me?
I’ve also try to append it to html but it’s not reading any value at all.
Jquery
$(document).ready(function () {
$.ajax({
url: `${siteRootUrl}api/order`,
// datatype: 'json',
type: "GET",
async: false,
success: function (res) {
result = res;
alert(result);
$.each(result, function(key,element){
alert(key , element)
})
result.forEach(function (result) {
$('#a').append("<tr><td>" + result.text + "</td></tr>");
});
},
error: function (res) {
alert('No Data');
}
});
});
my object
[HttpGet]
public string Get()
{
var myData = new
{
Host = @"sftp.myhost.gr",
UserName = "my_username",
Password = "my_password",
SourceDir = "/export/zip/mypath/",
FileName = 1
};
var bigCities = new List<string>()
{
"New York",
"London",
"Mumbai",
"Chicago"
};
// string.Join(", ", bigCities)
return myData.ToString();
}
2
Answers
Have you checked the response is that string or a json object
If the response is not json we need to convert string to json
JSON.parse
Change this line to
$.each/foreach will work not work if the value is not JSON
https://www.w3schools.com/js/js_json_parse.asp
Well, let’s start from how to nail it towards the way to investigate. Once you would know how to split the
javascript/Jquery
issue life would be easier.Check your response in client or Browser:
As you have only return below object:
So in browser or client site we should expect this object as output. Let’s see if we got that.
Note: As we can see the response, data has been returned as expected. Now we need to bind it with
HTML
or more specifically inTable
or anything else.Bind The Response in HTML:
Before starting, I want to point one thing very specifically abou the
data-structure
You are returningsingle string object
but searching that inloop
that is$.each(result
which is not correct.As its a single object you can directly read from the
res
. I did the same. See the example below:Output:
Controller:
I preferably written the controller as below however, you can continue yours one. I like this way: