How do I convert JSON data to display in HTML?
I am trying to display JSON data that I retrieve from an ajax call but I am unable to display any data despite getting the JSON object just fine.
<!DOCTYPE html>
<head>
<title></title>
<script src="jquery.js"></script>
</head>
<script>
$(document).ready(function(){
$.getJSON("http://servername:10000/_vti_bin/webservice/service1.svc/getListTitle",
{
username: "a",
password: "b",
list: "calendar",
},
function(data) {
alert(1);
// and the rest
}
)
});
</script>
<body>
</body
</html>
I don't get any alerts but using Fiddler I can see the JSON object.
{"GetListTitleResult":"Calendar"}
So what am I missing here? Any help appreciated. Thanks in advance.
EDIT: It seems like the code doesn't go all the way to the function(data) part. But firebug doesn't show any syntax 开发者_StackOverflow中文版errors either. I still get the JSON response through Fiddler. Any help here?
Change your code this way -
$.getJSON("http://servername:10000/_vti_bin/webservice/service1.svc/getListTitle",
{
username: "a",
password: "b",
list: "calendar",
},
function(data)
{
$.each(data, function(i,item)
{
alert(item);
});
});
In my opinion, these are the following mistakes that you've made -
- Since
data
itself will be a collection, you don't need to getdata.items
. Just pass thedata
as is to theeach
function. - The callback of the
each
iterator will be passed thekey
and thevalue
for each item in the collection. Hence,i
will beGetListTitleResult
, anditem
will beCalendar
.
That's not the method signature for getJSON()
. You don't need to key the success callback with success:
. You also have a few too many braces, brackets and semi-colons. Change it to
$.getJSON("http://servername:10000/_vti_bin/webservice/service1.svc/getListTitle",
{
username: "a",
password: "b",
list: "calendar",
format: "json"
},
function(data) {
console.log(data);
// and the rest
}
);
if you method looks like this:
public string getListTitle(string username, string password, string list, string format)
then your ajax data is good. If it's like this:
public string getListTitle(MyObject data)
then you need this:
{data: {
username: "a",
password: "b",
list: "calendar",
format: "json"
}
}
EDIT:
function(data) {
alert(data.GetListTitleResult);
});
精彩评论