mercredi 11 février 2015

Why can't I use my JSON data?


I am trying to read some JSON data from an AJAX function. Here is the AJAX I am using:



$.ajax({
type: 'POST',
cache: false,
url: 'http://ift.tt/1Dipz3b',
data: "{}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
var text = JSON.stringify(data);
$("#jsonData").html(text);
alert(text);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});


I also have use JSON.parse in place of stringify, and objects return undefined or not at all. This comes from a C# function which looks like this:



[WebMethod]
[ScriptMethod]
public static string GetCoords()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT TOP 10 * FROM DRAW ORDER BY DrawID DESC;", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
System.Diagnostics.Debug.WriteLine(serializer.Serialize(rows));
return serializer.Serialize(rows);
}
}
}


It is returning JSON data: Here is what it looks like on the Debugger Console and when I call the function in a paragraph tag:



[{"DrawID":925,"xCoord":466,"yCoord":201},{"DrawID":924,"xCoord":385,"yCoord":318},{"DrawID":923,"xCoord":768,"yCoord":159},{"DrawID":922,"xCoord":543,"yCoord":214},{"DrawID":921,"xCoord":329,"yCoord":172}]


However, when I send it to the paragraph tag in JQuery or call it in an HTML paragraph, here is what it looks like:



{"d":"[{\"DrawID\":925,\"xCoord\":466,\"yCoord\":201},{\"DrawID\":924,\"xCoord\":385,\"yCoord\":318},{\"DrawID\":923,\"xCoord\":768,\"yCoord\":159},{\"DrawID\":922,\"xCoord\":543,\"yCoord\":214},{\"DrawID\":921,\"xCoord\":329,\"yCoord\":172}]"}


I have two questions: (1) Why am I not able to use this data to insert the xCoords and yCoords into a canvas? I have tried many formats: (data.d[0].xCoord, d[0].xCoord, text.d[0].xCoord, text[0].xCoord, and so on). (2) Is the second format above going to be a problem in trying to extract that data for painting on the canvas (it's the backslashes that I am wondering about)?


Thanks.





Aucun commentaire:

Enregistrer un commentaire