在合适的位置数据库和显示部件回调的jQuery插件信息 [英] Call back jQuery widget information from Database and display widgets in proper locations

查看:160
本文介绍了在合适的位置数据库和显示部件回调的jQuery插件信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我终于能够成功地拯救我所有的部件信息与这帮助<一个href=\"http://stackoverflow.com/questions/27488457/pass-widget-data-using-json-and-saving-to-database\">question.

现在,我完全失去了对如何做到这一点,因为这是我第一次过做到这一点。我需要调用我回数据库中的信息,以正确显示我的小部件。

这是我的jQuery的仪表板。

  $(函数(){
        $('。dragbox')
        。每个(函数(){
            $(这).hover(函数(){
                $(本).find('H2')addClass(崩溃)。
            },函数(){
                $(本).find('H2')removeClass移除(崩溃)。
            })
            .find('H2')。悬停(函数(){
                $(本).find('配置'),CSS('知名度','看得见')。
            },函数(){
                $(本).find('配置'),CSS('知名度','隐藏')。
            })
            。点击(函数(){
                ('。dragbox内容')。$(本).siblings切换();
            })
            。结束()
            .find('配置')的CSS('知名度','隐藏')。
        });        $('列')排序({
            connectWith:.column',
            处理:H2,
            光标:搬家,
            占位符:'占位',
            forcePlaceholderSize:真实,
            不透明度:0.4,
            启动:函数(事件,UI){
                //火狐,Safari /铬火灾click事件拖动完成后,修复该
                //如果($ .browser.mozilla || $ .browser.safari)
                $(ui.item).find('dragbox的内容。')切换()。
            },
            停止:函数(事件,UI){
                ui.item.css({'顶部':'0','左':'0'}); //歌剧修复
                //如果($ browser.mozilla&安培;!&安培;!$ browser.safari)
                updateWidgetData();
            }
        })
        .disableSelection();
    });

我能保存到使用下面的,并使用一个处理器和一个数据类数据库。

 函数updateWidgetData(){
        变种项= [];
        $('列')。每个(函数(){
            VAR ColumnID的= $(本).attr('身份证');
            $('。dragbox',这一点)。每个(函数(一){
                变种倒塌= 0;
                如果($(本).find('。dragbox内容')。CSS('显示器')==无)
                    折叠= 1;
                //创建当前面板项目对象
                VAR项目= {
                    ID:$(本).attr(ID),
                    崩溃:崩溃了,
                    订购:我,
                    专栏:ColumnID的
                };
                //推项目对象为项目数组
                items.push(项目);
            });
        });
        //指定项目数组排序顺序JSON变量
        VAR排序顺序= {项目:项目};        $阿贾克斯({
            网址:/Handlers/SaveWidgets.ashx
            键入:POST,
            的contentType:应用/ JSON的;字符集= UFT-8,
            数据类型:JSON
            数据:JSON.stringify(排序顺序)
            成功:函数(响应){
                $(#控制台)HTML('&LT; D​​IV CLASS =成功&GT;仪表盘保存&LT; / DIV&GT;')。隐藏()淡入(1000);
                的setTimeout(函数(){
                    $('#控制台')淡出(1000)。
                },2000);
            },
            错误:功能(错误){
                警报(无法通过JSON。);
            }
        });

信息看起来在数据库中的方法是这样的..

下面是我的aspx,显示小部件(只显示2列和1小部件为每个为例)

 &LT; D​​IV CLASS =列ID =列1=服务器&GT;
     &LT; D​​IV CLASS =dragboxID =CurrentDealsWidget=服务器可见=假&GT;
          &LT; H2 =风格FONT-SIZE:14pt&GT;每个位置和LT当前优惠; / H&GT;
          &LT; D​​IV CLASS =dragbox内容&GT;
             &LT; ASP:GridView控件ID =gvCurrentLocationTotals=服务器的AutoGenerateColumns =FALSE
                    的DataKeyNames =InternallocationID&GT;
              //列
              &LT; / ASP:GridView的&GT;
          &LT; / DIV&GT;
      &LT; / DIV&GT;
 &LT; / DIV&GT;
 &LT; D​​IV CLASS =列ID =列2=服务器&GT;
      &LT; D​​IV CLASS =dragboxID =MonthlyDealsWidget=服务器可见=假&GT;
           &LT; H2 =风格FONT-SIZE:14pt&GT;每个位置和LT总加工优惠; / H&GT;
           &LT; D​​IV CLASS =dragbox内容&GT;
                小部件//内容
           &LT; / DIV&GT;
      &LT; / DIV&GT;
  &LT; / DIV&GT;

现在,我不知道我怎么会去这一点。我需要调用的信息从tWidgets表显示早在适当的排序。 0是列第一的位置,其次是1,2,3,我不知道我是否应该做这个页面加载,或者它会更好地使用处理做到这一点的过程。我不知道从哪里开始。我发现的唯一信息是如何在PHP这样做,但就是没有帮助我。如果任何人都可以在正确的方向指向我,那将是极大的AP preciated!

修改:我已经创建了一个检索窗口小部件的信息一个WebService,然后通过它来阿贾克斯页​​面加载。


  

Web服务


 公共类RetrieveWidgets:System.Web.Services.WebService
{
    [的WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)
    公开名单&LT; RetrieveWidgetsDAL&GT;的getWidgets()
    {
        康涅狄格州的SqlConnection =新的SqlConnection(ConfigurationManager.ConnectionStrings [dboCao]的ConnectionString);
        清单&LT; RetrieveWidgetsDAL&GT;的ListData =新的List&LT; RetrieveWidgetsDAL&GT;();
        INT getUserId;
        字符串username = HttpContext.Current.User.Identity.Name;
        conn.Open();
        使用(的SqlCommand cmdGetUserId =新的SqlCommand(选择用户ID FROM TUSER其中username = @用户,康涅狄格州))
        {
            cmdGetUserId.Parameters.AddWithValue(@用户名,用户名);
            getUserId = Convert.ToInt32(cmdGetUserId.ExecuteScalar());            System.Diagnostics.Debug.Write(---------------+ getUserId +---------------+使用者名称+ - --------);
        }        使用(的SqlCommand cmdGetWidgets =新的SqlCommand(SELECT标题,SortNo,晕倒,ColumnID的FROM tWidgets其中userid = @UserId,康涅狄格州))
        {
            cmdGetWidgets.Parameters.AddWithValue(@用户ID,getUserId);
            使用(RDR SqlDataReader的= cmdGetWidgets.ExecuteReader())
            {
                而(rdr.Read())
                {
                    RetrieveWidgetsDAL widgetDAL =新RetrieveWidgetsDAL();
                    widgetDAL.Title = rdr.GetString(0);
                    widgetDAL.SortNo = rdr.GetInt32(1);
                    widgetDAL.Collapsed = rdr.GetInt32(2);
                    widgetDAL.ColumnId = rdr.GetInt32(3);
                    listData.Add(widgetDAL);
                }
            }
        }
        conn.Close();
        返回的ListData;
    }
}


  

AJAX


  $(文件)。就绪(函数(){        $阿贾克斯({
            键入:邮报,
            的contentType:应用/ JSON的;字符集= UTF-8,
            网址:Web服务/ RetrieveWidgets.asmx /的getWidgets
            数据类型:JSON
            成功:函数(响应){
                警报(response.d); //尝试使用data.d
            },
            错误:功能(回购){
                的console.log(回购);
            },
            错误:功能(错误){
                $(#控制台)HTML('&LT; D​​IV CLASS =失败&GT;仪表盘可以空载&LT;!/ DIV&GT;')。CSS('知名度','看得见')fadeTo(600,1 );
                的setTimeout(函数(){
                    $('#控制台')延迟(500).fadeTo(600,0);
                },1000);
            }
        });
    });

现在,我的问题是,是否有使用jQuery基于数据库信息的部件,将它放在合适的位置的一种方式?

JSON的信息看起来是这样的。


  

{D:[{__类型:CentralLogin.Data.RetrieveWidgetsDAL,标题:CurrentDealsWidget,SortNo:0,晕倒:0,ColumnID的:1},{__type:CentralLogin.Data.RetrieveWidgetsDAL,题目: StorePayrollWidget,SortNo:1,晕倒:0,ColumnID的:1},{__type:CentralLogin.Data.RetrieveWidgetsDAL,标题:ObjectiveWidget,SortNo:2,折叠:0,ColumnID的:1},{__type: CentralLogin.Data.RetrieveWidgetsDAL,标题:ReportWidget,SortNo:0,晕倒:0,ColumnID的:2}



解决方案

\r
\r

$(文件)。就绪(函数(){\r
        变种响应='{D:[{__类型:CentralLogin.Data.RetrieveWidgetsDAL,标题:CurrentDealsWidget,SortNo:0,折叠:0,ColumnID的:1}, {__type:CentralLogin.Data.RetrieveWidgetsDAL,标题:StorePayrollWidget,SortNo:1,折叠:0,ColumnID的:1},{__type:CentralLogin.Data。 RetrieveWidgetsDAL,标题:ObjectiveWidget,SortNo:2,折叠:0,ColumnID的:1},{__type:CentralLogin.Data.RetrieveWidgetsDAL,标题:ReportWidget SortNo:0,折叠:0,ColumnID的:2}]}';\r
        变种TE = JSON.parse(响应)\r
\r
        功能sortResults(道具,ASC){\r
            te.d = te.d.sort(功能(A,B){\r
                如果(ASC)回报(A [道具]&GT; B [道具])? 1:((一[道具]&LT; B [道具])-1:0);\r
                否则返回(B [道具]&gt;将[道具])? 1:((B [道具] LT; A [道具])-1:0);\r
            });\r
        }\r
        sortResults('SortNo',真);\r
        对于(VAR I = 0; I&LT; te.d.length;我++){\r
            $('#测试UL)追加('&LT;立GT;'+ te.d [I] .title伪+'&LT; /李&GT;')\r
        }\r
    });

\r

&LT;脚本SRC =htt​​ps://ajax.googleapis.com/ajax /libs/jquery/1.10.2/jquery.min.js\"></script>\r
&LT; D​​IV ID =测试&GT;&LT; UL&GT;&LT; / UL&GT;&LT; / DIV&GT;

\r

\r
\r

这可能会帮助你。

我不是一个C#或asp.net开发。但我见过你的应对它不是在正确的JSON可能是你错过了格式化为JSON你的反应。
所以我疯了你的JSON的一些变化只是将所有的密钥字符串,这就是下面提了。

新的Json

  {
    D:
        [
            {
                __type:CentralLogin.Data.RetrieveWidgetsDAL,
                标题:CurrentDealsWidget
                SortNo:0,
                折叠:0,
                ColumnID的:1
            },
            {
                __type:CentralLogin.Data.RetrieveWidgetsDAL,
                标题:StorePayrollWidget
                SortNo:1,
                折叠:0,
                ColumnID的:1
            },
            {
                __type:CentralLogin.Data.RetrieveWidgetsDAL,
                标题:ObjectiveWidget
                SortNo:2,
                折叠:0,
                ColumnID的:1
            },
            {
                __type:CentralLogin.Data.RetrieveWidgetsDAL,
                标题:ReportWidget
                SortNo:0,
                折叠:0,
                ColumnID的:2
            }
        ]
    }

JavaScript

只需添加下面的脚本在阿贾克斯的成功的功能。

  VAR TE = JSON.parse(响应)
                        功能sortResults(道具,ASC){
                            te.d = te.d.sort(功能(A,B){
                                如果(ASC)回报(A [道具]&GT; B [道具])? 1:((一[道具]&LT; B [道具])-1:0);
                                否则返回(B [道具]&gt;将[道具])? 1:((B [道具] LT; A [道具])-1:0);
                            });
                        }                        sortResults('SortNo',真);                        对于(VAR I = 0; I&LT; te.d.length;我++){
                            $('#测试UL)追加('&LT;立GT;'+ te.d [I] .title伪+'&LT; /李&GT;');
                            的console.log(te.d [I])
                        }

HTML

 &LT; D​​IV ID =测试&GT;
        &LT; UL&GT;        &LT; / UL&GT;
&LT; / DIV&GT;

一旦我们使用JSON工作那么所有的关键应该是字符串。

I was finally able to save all my widget information successfully with the help from this question.

Now, I'm completely lost on how to do this, as it is the first time I've ever had to do this. I need to call back my database information to display my widgets properly.

This is my jQuery for the dashboard.

$(function () {
        $('.dragbox')
        .each(function () {
            $(this).hover(function () {
                $(this).find('h2').addClass('collapse');
            }, function () {
                $(this).find('h2').removeClass('collapse');
            })
            .find('h2').hover(function () {
                $(this).find('.configure').css('visibility', 'visible');
            }, function () {
                $(this).find('.configure').css('visibility', 'hidden');
            })
            .click(function () {
                $(this).siblings('.dragbox-content').toggle();
            })
            .end()
            .find('.configure').css('visibility', 'hidden');
        });

        $('.column').sortable({
            connectWith: '.column',
            handle: 'h2',
            cursor: 'move',
            placeholder: 'placeholder',
            forcePlaceholderSize: true,
            opacity: 0.4,
            start: function (event, ui) {
                //Firefox, Safari/Chrome fire click event after drag is complete, fix for that  
                //if ($.browser.mozilla || $.browser.safari)
                $(ui.item).find('.dragbox-content').toggle();
            },
            stop: function (event, ui) {
                ui.item.css({ 'top': '0', 'left': '0' }); //Opera fix  
                //if (!$.browser.mozilla && !$.browser.safari)
                updateWidgetData();
            }
        })
        .disableSelection();
    });  

I am able to save to the database using the below and using a Handler and an data class.

function updateWidgetData() {
        var items = [];
        $('.column').each(function () {
            var columnId = $(this).attr('id');
            $('.dragbox', this).each(function (i) {
                var collapsed = 0;
                if ($(this).find('.dragbox-content').css('display') == "none")
                    collapsed = 1;
                //Create Item object for current panel  
                var item = {
                    id: $(this).attr('id'),
                    collapsed: collapsed,
                    order: i,
                    column: columnId
                };
                //Push item object into items array  
                items.push(item);
            });
        });
        //Assign items array to sortorder JSON variable  
        var sortorder = { items: items };

        $.ajax({
            url: "/Handlers/SaveWidgets.ashx",
            type: "POST",
            contentType: "application/json; charset=uft-8",
            dataType: "json",
            data: JSON.stringify(sortorder),
            success: function (response) {
                $("#console").html('<div class="success">Dashboard Saved</div>').hide().fadeIn(1000);
                setTimeout(function () {
                    $('#console').fadeOut(1000);
                }, 2000);
            },
            error: function (error) {
                alert("Failed passing json.");
            }
        });

The way the information looks in the database is like this..

Here is my aspx that shows the widgets (only showing 2 columns, and 1 widget for each for example)

<div class="column" id="column1" runat="server">
     <div class="dragbox" id="CurrentDealsWidget" runat="server" visible="false">
          <h2 style="font-size: 14pt">Current Deals per Location</h2>
          <div class="dragbox-content">
             <asp:GridView ID="gvCurrentLocationTotals" runat="server" AutoGenerateColumns="False"
                    DataKeyNames="InternallocationID">
              //columns
              </asp:GridView>
          </div>
      </div>
 </div>
 <div class="column" id="column2" runat="server">
      <div class="dragbox" id="MonthlyDealsWidget" runat="server" visible="false ">
           <h2 style="font-size: 14pt">Total Processed Deals per Location</h2>
           <div class="dragbox-content">
                //content for the widget
           </div>
      </div>
  </div>

Now, I'm not sure how I would go about this. I need to call the information back from the tWidgets table and display in the proper sort. 0 being the first position in the column, followed by 1, 2, 3. I'm not sure if I should do this on the page load, or if it would be better to use a handler to do this process. I'm not sure where to start. The only information that I have found is how to do this in php but that is of no help to me. If anyone can point me in the right direction, that will be greatly appreciated!

EDIT: I have created a WebService that retrieves the widget information and then passes it to ajax on page load.

Web Service

public class RetrieveWidgets : System.Web.Services.WebService
{
    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public List<RetrieveWidgetsDAL> GetWidgets()
    {
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dboCao"].ConnectionString);
        List<RetrieveWidgetsDAL> listData = new List<RetrieveWidgetsDAL>();
        int getUserId;
        string userName = HttpContext.Current.User.Identity.Name;
        conn.Open();
        using (SqlCommand cmdGetUserId = new SqlCommand("SELECT UserId FROM tUser WHERE UserName = @UserName", conn))
        {
            cmdGetUserId.Parameters.AddWithValue("@UserName", userName);
            getUserId = Convert.ToInt32(cmdGetUserId.ExecuteScalar());

            System.Diagnostics.Debug.Write(" --------------- " + getUserId + " --------------- " + userName + " ---------");
        }

        using (SqlCommand cmdGetWidgets = new SqlCommand("SELECT Title, SortNo, Collapsed, ColumnId FROM tWidgets WHERE UserId = @UserId", conn))
        {
            cmdGetWidgets.Parameters.AddWithValue("@UserId", getUserId);
            using (SqlDataReader rdr = cmdGetWidgets.ExecuteReader())
            {
                while (rdr.Read())
                {
                    RetrieveWidgetsDAL widgetDAL = new RetrieveWidgetsDAL();
                    widgetDAL.Title = rdr.GetString(0);
                    widgetDAL.SortNo = rdr.GetInt32(1);
                    widgetDAL.Collapsed = rdr.GetInt32(2);
                    widgetDAL.ColumnId = rdr.GetInt32(3);
                    listData.Add(widgetDAL);
                }
            }
        }
        conn.Close();
        return listData;
    }
}

ajax

$(document).ready(function () {

        $.ajax({
            type: "Post",
            contentType: "application/json; charset=utf-8",
            url: "Webservices/RetrieveWidgets.asmx/GetWidgets",
            dataType: "json",
            success: function (response) {
                alert(response.d);  // try using data.d
            },
            error: function (repo) {
                console.log(repo);
            },
            error: function (error) {
                $("#console").html('<div class="fail">Dashboard could no load!</div>').css('visibility', 'visible').fadeTo(600, 1);
                setTimeout(function () {
                    $('#console').delay(500).fadeTo(600, 0);
                }, 1000);
            }
        });
    });

Now, my question is, is there a way to use jQuery to place the widgets into their proper location based on the database information?

The json information looks like this..

{d:[{__type:"CentralLogin.Data.RetrieveWidgetsDAL", Title:"CurrentDealsWidget", SortNo:0, Collapsed:0, ColumnId:1}, {__type:"CentralLogin.Data.RetrieveWidgetsDAL", Title:"StorePayrollWidget", SortNo:1, Collapsed:0, ColumnId:1}, {__type:"CentralLogin.Data.RetrieveWidgetsDAL", Title:"ObjectiveWidget", SortNo:2, Collapsed:0, ColumnId:1}, {__type:"CentralLogin.Data.RetrieveWidgetsDAL", Title:"ReportWidget", SortNo:0, Collapsed:0, ColumnId:2}

解决方案

$(document).ready(function() {
        var response = '{"d":[{"__type":"CentralLogin.Data.RetrieveWidgetsDAL", "Title":"CurrentDealsWidget", "SortNo":0, "Collapsed":0, "ColumnId":1}, {"__type":"CentralLogin.Data.RetrieveWidgetsDAL", "Title":"StorePayrollWidget", "SortNo":1, "Collapsed":0, "ColumnId":1}, {"__type":"CentralLogin.Data.RetrieveWidgetsDAL", "Title":"ObjectiveWidget", "SortNo":2, "Collapsed":0, "ColumnId":1}, {"__type":"CentralLogin.Data.RetrieveWidgetsDAL", "Title":"ReportWidget", "SortNo":0, "Collapsed":0, "ColumnId":2}]}';
        var te = JSON.parse(response)

        function sortResults(prop, asc) {
            te.d = te.d.sort(function(a, b) {
                if (asc) return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
                else return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
            });
        }
        sortResults('SortNo', true);
        for (var i = 0; i < te.d.length; i++) {
            $('#test ul').append('<li>'+te.d[i].Title+'</li>')
        }
    });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<div id="test"><ul></ul></div>

This might help you.

I am not a c# or asp.net developer. But I seen you response it's not in proper json might be you miss to Format your response as a JSON . So I mad some changes in your JSON just place all key as string and that's mention below.

NEW Json

{
    "d":
        [
            {
                "__type":"CentralLogin.Data.RetrieveWidgetsDAL", 
                "Title":"CurrentDealsWidget", 
                "SortNo":0, 
                "Collapsed":0, 
                "ColumnId":1
            }, 
            {
                "__type":"CentralLogin.Data.RetrieveWidgetsDAL", 
                "Title":"StorePayrollWidget", 
                "SortNo":1, 
                "Collapsed":0, 
                "ColumnId":1
            }, 
            {
                "__type":"CentralLogin.Data.RetrieveWidgetsDAL", 
                "Title":"ObjectiveWidget", 
                "SortNo":2, 
                "Collapsed":0, 
                "ColumnId":1
            }, 
            {
                "__type":"CentralLogin.Data.RetrieveWidgetsDAL", 
                "Title":"ReportWidget", 
                "SortNo":0, 
                "Collapsed":0, 
                "ColumnId":2
            }
        ]
    }

javaScript

Just add below script in your ajax's success function.

var te = JSON.parse(response)
                        function sortResults(prop, asc) {
                            te.d = te.d.sort(function(a, b) {
                                if (asc) return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
                                else return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
                            });
                        }

                        sortResults('SortNo', true);

                        for (var i = 0; i < te.d.length; i++) {
                            $('#test ul').append('<li>' + te.d[i].Title + '</li>');
                            console.log(te.d[i])
                        }

HTML

<div id="test">
        <ul>

        </ul>
</div>

Once we working with Json then all key should be in string.

这篇关于在合适的位置数据库和显示部件回调的jQuery插件信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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