通过AJAX asp.net问题接受JSON [英] receiving json via ajax asp.net issue

查看:104
本文介绍了通过AJAX asp.net问题接受JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想接收使用AJAX asp.net一个JSON数据。
我有一个Web服务与Web方法 -

I am trying to receive a json data using ajax asp.net. i have got a web service with a web method -

[WebMethod]
public List<Song> GetSongListByMood(string Mood)
{
    SongBL songbl = new SongBL();
    return songbl.GetSongListByMoodBL(Mood);
}

和我有JavaScript的code -

and i have got the javascript code -

        $(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服务器的数据,并把数据在播放列表中的变量

now basically what im trying to do is get the data from the server using ajax in json format and put the data in the playlist variable

推荐答案

您需要做出一些改变。


  1. 更​​改方法返回一个字符串而不是列表&LT;宋方式&gt;

添加一个using语句使用System.Web.Script.Serialization

add a using statement using System.Web.Script.Serialization.

创建的JavaScriptSerializer 的实例,并用它来序列化对象,并返回结果。

Create an instance of JavaScriptSerializer and use that to serialize your object and return the results.

所以...

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 code充分利用现有的jQuery方法:

Change your AJAX code to leverage the JQuery methods available:

$("#slider a").click(function () {
    $.ajax({
        "url" : "AvironaService.asmx/GetSongListByMood",
        "type" : "post",
        "data" : {"Mood" : $(this).text()},
        "dataType" : "json"
        "success" : function(data){
          myPlaylist.playlist = data;
        }
    });
});

这篇关于通过AJAX asp.net问题接受JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆