1

我的問題是,以下代碼在Firefox和Chrome中正常工作,但在IE9中無效。它表示位置未定義或爲空。在IE9中未識別自動完成

我的自動完成代碼如下:

$("#id_location").autocomplete({ 
source: function(request, response) { 

$.ajax({ 
       url: "{% url 'food.views.search_location' %}", 
       dataType: "json", 
       data:{ 
        maxRows: 5, 
        starts_with: request.term, 
       }, 
       success: function(data) { 
        response($.map(data.location, function(item) { 
         return { 
          label: item.label, 
          value: item.value 
         } 
        })); 
       } 
      }); 
     }, 
     minLength: 1,  

     focus: function(event,ui){ 
    //prevent value insert on focus 
    $("#id_location").val(ui.item.label); 
     return false; //Prevent widget from inserting value 
     }, 

    select: function(event, ui) { 
     $('#id_location').val(ui.item.label); 
     $('#id_locationID').val(ui.item.value); 
     return false; // Prevent the widget from inserting the value. 
     }, 


    }); 

我backened代碼如下:

def search_location(request): 
""" 
Jason data for location 
search autocomplete 
""" 
    q = request.GET['starts_with'] 
    r = request.GET['maxRows'] 
    ret = [] 
    listlocation = USCities.objects.filter(name__istartswith=q)[:r] 
    for i in listlocation: 
     ret.append({'label':i.name+','+i.state.name+' '+i.state.abbr,'value':i.id}) 

    ret = {'location':ret} 
    data = simplejson.dumps(ret) 
    return HttpResponse(data, 
     content_type='application/json; charset=utf8' 
    ) 

幫助將不勝感激!

+0

你在哪裏得到未定義的位置或null?在服務器端還是在JS?你也可以告訴代碼中錯誤發生的地方嗎? – Babu 2012-07-27 06:17:28

回答

2

您的問題是在這條線:

starts_with: request.term, 

這是一個對象結構中的最後元件,並且它具有在末端具有逗號。

這在技術上是非法的Javascript,但IE是唯一的強制執行它的瀏覽器。這就是爲什麼你會在IE中遇到錯誤,而不是其他瀏覽器。

同樣的錯誤也發生在第33行(即幾乎在代碼的結尾處),其中有一個閉合大括號,後面跟着一個對象結構末尾的非法逗號},

如果您在諸如JSHint之類的工具中驗證代碼,則很容易出現此錯誤。

希望有所幫助。