【问题标题】:C# Webservice json data jquery ui with custom formatting具有自定义格式的 C# Webservice json 数据 jquery ui
【发布时间】:2015-12-22 12:46:02
【问题描述】:

我正在使用 asp.net webservice 在 jQuery UI 自动完成插件中使用它,这是我得到的数据。

{"d":[
    {
        "__type":"WebS.Model.SearchModel",
        "MainCommodityId":1,
        "MainCommodityName":"Pulses",
        "SubcommodityId":3,
        "SubCommodityName":"Urid Dal",
        "BrandId":3,
        "BrandName":"President"
    },
    {
        "__type":"WebS.Model.SearchModel",
        "MainCommodityId":1,
        "MainCommodityName":"Pulses",
        "SubcommodityId":1,
        "SubCommodityName":"Red Gram",
        "BrandId":4,
        "BrandName":"President"
    }
    ]
}

这是我正在使用的脚本:

$(document).ready(function () {
    $(".input-search").autocomplete({
        source: function (request, response) {
            $.ajax({
                url: '/WebServices/GetAllBrandNames.asmx/getAllBrands',
                data: "{ 'data': '" + request.term + "'}",
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function (data) {
                    response($.map(data.d, function (item) {
                        return {
                            value: item.BrandName,
                            label: item.SubCommodityName
                        }
                    }))
                },
                error: function (response) {
                    alert('error');
                },
                failure: function (response) {
                    alert('faii');
                }
            });
        },
        select: function (e, i) {
            console.log(i.MainCommodityId);
            console.log(i.SubcommodityId);
            console.log(i.BrandId);
        },
        minLength: 1
    }).autocomplete("instance")._renderItem = function (ul, item) {
        return $("<li></li>")
            .data("item.autocomplete", item)
            .append("<a>" + "" + item.BrandName + " in " + item.MainCommodityName + " - " + item.SubCommodityName + "</a>")
            .appendTo(ul);
    };
});

问题是:

  1. 当我尝试输入关键字时说:pre 上述输出以 json 格式出现。但是,该列表只返回一个“总统”项目,它应该显示 2 个项目。
  2. 添加.autocomplete("instance")._renderItem 函数后,列表显示“未定义中的未定义 - 未定义”而不是值。
  3. console.logs 在选择项目后也未定义。

如何解决这些问题?

【问题讨论】:

  • 你有没有尝试将 var data=JSON.parse(data) 作为 $.ajax 中成功的第一行?
  • 是的。我也试过了。
  • 如果数据能够编码,那么返回 json 可能会出现问题尝试创建一个全局 json 对象的数组并将 json 对象推入该数组并返回。
  • 我可以看到您的测试站点上出现了两个“总统”。只是您的导航栏隐藏了它。关于未定义。您可以尝试在使用$( ".input-search" ).on( "selectmenuselect", function( event, ui ) {do something..} ); 附加&lt;li&gt; 项目后添加选择事件@
  • 所以这是为了防止focusselect 上的默认操作,并使用_renderItem 自定义下拉菜单,除此之外我猜一切都是正确的。不错(+1)。

标签: javascript jquery json jquery-ui jquery-ui-autocomplete


【解决方案1】:

select 事件的默认行为是使用 ui.item.value 更新输入。此代码在您的事件处理程序之后运行。

使用event.preventDefault()return false 简单地阻止selectfocus 上的默认操作,并使用_renderItem 进行自定义下拉菜单。

focus: function(event, ui) {
   // prevent autocomplete from updating the textbox
   event.preventDefault(); // or return false;
}

select: function(event, ui) {
   // prevent autocomplete from updating the textbox
   event.preventDefault(); 
   //do something
}

参考资料:

  1. jQuery UI Autocomplete Examples
  2. Example 2

【讨论】:

    【解决方案2】:

    终于,我实现了我想要的。回答我的问题,因为它可能对某人有帮助。

    javascript:

    $(document).ready(function () {
        $(".input-search").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: '/WebServices/GetAllBrandNames.asmx/getAllBrands',
                    data: "{ 'data': '" + request.term + "'}",
                    dataType: "json",
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    success: function (data) {
                        response($.map(data.d, function (item) {
                  // don't forget to $.map to (data.d where d is the top node
                            return {
                 // assign values from json response for further use
                                brandid: item.BrandId,
                                brand: item.BrandName,
                                maincommodityid: item.MainCommodityId,
                                maincommodity: item.MainCommodityName,
                                subcommodityid: item.SubcommodityId,
                                subcommodity: item.SubCommodityName
                            }
                        }));
                    },
                    error: function (response) {
                        alert('Server Error. Please try again.');
                    },
                    failure: function (response) {
                        alert('Failed to get result');
                    }
                });
            },
            focus: function (event, ui) {
                // prevent autocomplete from updating the textbox
                event.preventDefault();
            },
            select: function (event, ui) {
                // prevent autocomplete from updating the textbox
                event.preventDefault();
                // do further action here such as assigning id to hidden field etc. 
                $(".input-search").val(ui.item.brand);
                // navigate to the selected item's url ex: /catalogue/1/1/pulses/red-gram/4/president
                var str = "/catalogue/" + ui.item.maincommodityid + "/" +
                     ui.item.subcommodityid + "/" + $.trim(ui.item.maincommodity.replace(/\s+/g, '-').toLowerCase()) + "/" +
                     $.trim(ui.item.subcommodity.replace(/\s+/g, '-').toLowerCase()) + "/" + ui.item.brandid + "/" +
                      $.trim(ui.item.brand.replace(/\s+/g, '-').toLowerCase());
                window.location = str;
            },
            minLength: 3
        }).autocomplete("instance")._renderItem = function (ul, item) {
            // get values and create custom display
            var $a = $("<a></a>");                  
            $("<strong></strong>").text(item.brand).appendTo($a);
            $("<span></span>").text(" in ").appendTo($a);
            $("<span></span>").text(item.subcommodity).appendTo($a);
            return $("<li></li>").append($a).appendTo(ul);
        };
    });
    

    CSS:

        ul.ui-front {
            z-index: 1200; // change z-index according to your UI.
        }
    

    【讨论】:

      【解决方案3】:

      通常我是这样做的,它的工作原理。

      $(document).ready(function () {
      var jsondata=array();
      $.post("/WebServices/GetAllBrandNames.asmx/getAllBrands",{data: request.term},function(data){
      var data=JSON.parse(data);
      $.each(data.d, function( index, value ) {
        jsondata[index].value=value;
       });
      $(".input-search").autocomplete({
          source:jsondata,
          //other property and events
       })
      });
      

      我的意思是在完成请求后应用源 JSON,因为有时如果 AJAX 需要一些时间来加载执行指针,仍然会执行其余代码而不等待响应。

      我没有测试这段代码,但我总是这样做,从来没有遇到过你的错误。祝你好运

      【讨论】:

      • 不,这不起作用。抛出错误:{ 'data': '" + request.term
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多