我正在尝试使用ajax asp.net接收json数据。 我有一个Web方法的Web服务 -
[WebMethod]
public List<Song> GetSongListByMood(string Mood)
{
SongBL songbl = new SongBL();
return songbl.GetSongListByMoodBL(Mood);
}
我有javascript代码 -
$(document).ready(function () {
var cssSelector = {
jPlayer: "#jquery_jplayer_1",
cssSelectorAncestor: "#jp_container_1"
};
var playlist = [];
var options = {
swfPath: "./js",
supplied: "mp3"
};
var myPlaylist = new jPlayerPlaylist(cssSelector, playlist, options);
$("#slider a").click(function () {
var mood = $(this).text();
var xhr = new XMLHttpRequest();
var url = "AvironaService.asmx/GetSongListByMood";
xhr.open("POST", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var obj = JSON.parse(xhr.responseXML.text);
myPlaylist.playlist = obj;
}
};
var contentType = "application/x-www-form-urlencoded"
xhr.setRequestHeader("Content-Type", contentType);
var qs = 'Mood=' + mood;
xhr.send(qs);
});});
现在基本上我试图做的是使用json格式的ajax从服务器获取数据并将数据放入播放列表变量
答案 0 :(得分:0)
您需要进行一些更改。
更改您的方法以返回string
而不是List<Song>
。
添加使用声明using System.Web.Script.Serialization
。
创建JavaScriptSerializer
的实例并使用它来序列化您的对象并返回结果。
因此...
using System.Web.Script.Serialization;
[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public string GetSongListByMood(string Mood)
{
SongBL songbl = new SongBL();
var jss = new JavaScriptSerializer();
return jss.Serialize(songbl.GetSongListByMoodBL(Mood));
}
更改您的AJAX代码以利用可用的JQuery方法:
$("#slider a").click(function () {
$.ajax({
"url" : "AvironaService.asmx/GetSongListByMood",
"type" : "post",
"data" : {"Mood" : $(this).text()},
"dataType" : "json"
"success" : function(data){
myPlaylist.playlist = data;
}
});
});