从WebMethod获取Json数据到应用程序



我想从Web方法获取Json数据。在这里,我想获得新闻和演讲者的两个数据,但这里只工作新闻。(无法获得扬声器)

这是我的存储过程

ALTER procedure [dbo].[LoadDayEvents] 
@Date date
as 
begin
select News,Speaker from Eventstbl
where DateToBePublished = CONVERT(date, @Date)
end

这是我的网络方法

 [WebMethod, ScriptMethod]
public static string SelectEventDate(string date)
{
    string News= "";
    string Speaker = "";
    try
    {
        SqlCommand comld = new SqlCommand("LoadDayEvents", conDB);
        comld.CommandType = CommandType.StoredProcedure;
        comld .Parameters.Add("@Date", SqlDbType.Date);
        comld .Parameters["@Date"].Value = DateTime.Parse(date).Date;
        if (conDB.State == ConnectionState.Closed)
            conDB.Open();
        News = comld .ExecuteScalar().ToString();
        Speaker = comld .ExecuteScalar().ToString();  // Thisone is not working
    }
    catch (Exception ee) { }
    finally { conDB.Close(); }
    return News;
}

在这里我使用 Ajax/Json 来获取它

  <script type="text/javascript">
    $(document).ready(function () {
        var urinews = '<%= ResolveUrl("WebMethods.aspx/SelectEventDate") %>';
        var localtime = new Date();
        var today = localtime.getFullYear() + '/' + (localtime.getMonth() + 1) + '/' + localtime.getDate();

        $.ajax({
            type: "POST",
            url: urinews,
            data: "{ date: '" + today + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: true,
            cache: false,
            success: function (msg) {
                $("#daily_news_Selection").append("<p>" + msg.d + "</p>");
            },
            error: function (x, e) {
            }
        });
    });
</script>

你可以返回自定义类

 var newsAndSpeaker = new NewsAndApeaker() { News = News, Speaker = Speaker}; //or define a custom class that has these two properties
 return newsAndSpeaker;

在 Javascript 上,您可以使用以下方法访问这两个变量

msg.d.News //news
msg.d.Speaker

或者,您可以返回字符串列表

 var newsAndSpeaker = new List<string>() { News, Speaker}; //or define a custom class that has these two properties
 return newsAndSpeaker;

在Javascript上,你可以像数组一样访问这两个变量。

msg.d[0] //mews
msg.d.[1] //speaker

如果你的问题是为什么你的第二个房产没有被填充,那么标题似乎是错误的

最新更新