简体   繁体   English

为什么在浏览器中不显示JQuery自动完成结果?

[英]Why are JQuery autocomplete results not showing in browser?

I have a working fiddle, but the autocomplete does not display anything in the browser. 我有一个正在工作的小提琴,但是自动完成功能在浏览器中不显示任何内容。 The fiddle can be seen here: Working Fiddle 小提琴可以在这里看到: 工作小提琴

In the HTML, I have one input element for testing purposes: 在HTML中,我有一个用于测试目的的输入元素:

<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>

<script type ="text/javascript" src="myScripts.js"></script>
<script type ="text/javascript" src="jquery.csv-0.71.js"></script>
<script type ="text/javascript" src="csvToArray.v2.1.js"></script>
</head>


<body>
<div data-role="page" id="main">

    <div data-role="header">
        <h1>Test</h1>
    </div>

    <div id="contentDiv" data-role="content">   
        <input type="text" id="food" placeholder="Type (First Name) Here" />        
    </div>

</div>
</body>

In my javascript, I am initializing a json variable by reading text from a file. 在我的JavaScript中,我通过从文件中读取文本来初始化json变量。 I have tested that my initialization is successful by displaying an alert of my json variable. 我已经通过显示json变量警报来测试初始化​​是否成功。 I am trying to use that json variable as the source in my autocomplete. 我正在尝试使用该json变量作为自动填充中的源。 Below, I have simplified my javascript by hard coding the initialization of the json variable in order to narrow down the problem: 下面,我通过对json变量的初始化进行硬编码来简化JavaScript,以缩小问题的范围:

var jsonVersion =       
[{"description":"mac and cheese", "servingSize":"1 cup", "calories":"500"},
 {"description":"slice of pizza", "servingSize":"1 slice", "calories":"400"},
 {"description":"oreo cookie", "servingSize":"1 cookie", "calories":"100"},
 {"description":"salad", "servingSize":"1 cup", "calories":"50"},
 {"description":"apple", "servingSize":"1 apple", "calories":"70"}];

$('#food').autocomplete({
                     source: jsonVersion,
                     select: function (event, ui) {
                     selectedObj = ui.item;
                     alert("selected object=" + selectedObj.value);
                                                    },
                     minLength: 1
                        });

Any idea why this would work in the fiddle but not in the browser? 知道为什么这会在小提琴中起作用而不在浏览器中起作用吗? I am not getting any browser errors. 我没有任何浏览器错误。 Simply nothing is being displayed when I type in the textbox. 当我在文本框中键入内容时,根本没有任何显示。

EDIT 编辑

Perhaps it is in the way I am populating my jsonVersion - although when I print the jsonVersion via "alert", it looks right. 也许这是我填充jsonVersion的方式-尽管当我通过“ alert”打印jsonVersion时,它看起来正确。 Any advice on what I am doing wrong here would be appreciated. 对于我在这里做错的任何建议,将不胜感激。 Here is the entire javascript file. 这是整个javascript文件。 "data" is an array of arrays and I am looping through each of those arrays to create an object, in turn creating an array of Objects. “数据”是一个数组数组,我在每个数组中循环创建一个对象,然后创建一个对象数组。 Then I convert the array of objects to json using stringify: 然后,我使用stringify将对象数组转换为json:

$(function ($) {
    var jsonVersion;
    var arrayOfObjects;
    $.ajax({
            type: "GET",
            url: "test.js",
            dataType: "text",
            success: function(data) {
                                    data = $.csv.toArrays(data);
                                    arrayOfObjects = new Array();
                                    for(var i=1; i<data.length; i++)//skipping over header
                                    {
                                        var foodObject = new Object();
                                        foodObject.label = data[i][1];
                                        foodObject.weight = data[i][2];
                                        foodObject.servingSize = data[i][3];
                                        foodObject.calories = data[i][4];
                                        arrayOfObjects.push(foodObject);
                                    }
                                    jsonVersion = JSON.stringify(arrayOfObjects);
                                    alert(jsonVersion); 
                                    }
            });

    $('#food').autocomplete({
                            source: jsonVersion,
                            select: function (event, ui) {
                            selectedObj = ui.item;
                            alert("selected object=" + selectedObj.value);
                                                            },
                            minLength: 1
                            });
})

You have two major problems: 您有两个主要问题:

  1. You're passing a string to the source option of autocomplete. 您正在将字符串传递给自动完成功能的source选项。 When you do this, the widget attempts to use that string as a URL to retrieve results from. 执行此操作时,窗口小部件将尝试使用该字符串作为URL来检索结果。 Since this string is a JSON representation of the array you built as the result of the AJAX call, this is obviously not going to work the way you expect it to. 由于此字符串是作为AJAX调用结果而构建的数组的JSON表示形式,因此,这显然无法按预期的方式工作。 You should simply use arrayOfObjects instead. 您应该只使用arrayOfObjects

  2. You're initializing the autocomplete widget outside of the success callback for your AJAX request. 您正在为AJAX请求的success回调之外初始化自动完成小部件。 This means that the autocomplete widget is initialized with an empty source. 这意味着自动完成小部件将使用空源进行初始化。 You can fix by simply moving the initialization into the success callback. 您可以通过简单地将初始化移到success回调中来进行修复。

Fixing both of these things should fix your issues: 解决这两个问题都可以解决您的问题:

$(function ($) {
    $.ajax({
        type: "GET",
        url: "test.js",
        dataType: "text",
        success: function(data) {
            data = $.csv.toArrays(data);
            var arrayOfObjects = [];
            for(var i=1; i<data.length; i++)//skipping over header
            {
                var foodObject = new Object();
                foodObject.label = data[i][1];
                foodObject.weight = data[i][2];
                foodObject.servingSize = data[i][3];
                foodObject.calories = data[i][4];
                arrayOfObjects.push(foodObject);
            }

            $('#food').autocomplete({
                source: arrayOfObjects,
                select: function (event, ui) {
                    selectedObj = ui.item;
                    alert("selected object=" + selectedObj.value);
                },
                minLength: 1
            });            
        }
    });
});

Looks like your script is not inside dom ready handler. 看起来您的脚本不在dom ready处理程序内。

In jsfiddle, in the second dropdown in the left side panel onload tells the app to add a wrapping onload handler for the script - if you select on head it will not work fiddle 在的jsfiddle,在左侧面板中的第二个下拉onload告诉该应用添加一个包裹onload处理的脚本-如果你选择on head ,它不会工作拨弄

jQuery(function ($) {
    var jsonObject = [{
        "label": "mac and cheese",
            "servingSize": "1 cup",
            "calories": "500"
    }, {
        "label": "slice of pizza",
            "servingSize": "1 slice",
            "calories": "400"
    }, {
        "label": "oreo cookie",
            "servingSize": "1 cookie",
            "calories": "100"
    }, {
        "label": "salad",
            "servingSize": "1 cup",
            "calories": "50"
    }, {
        "label": "apple",
            "servingSize": "1 apple",
            "calories": "70"
    }];

    $('#food').autocomplete({
        source: jsonObject,
        select: function (event, ui) {
            selectedObj = ui.item;

            alert("selected object=" + selectedObj.value);
        },
        minLength: 1
    });
})

Demo: Fiddle 演示: 小提琴

Update: 更新:

$(function ($) {
    var arrayOfObjects = [];
    $.ajax({
        type: "GET",
        url: "test.js",
        dataType: "text",
        success: function (data) {
            data = $.csv.toArrays(data);
            for (var i = 1; i < data.length; i++) //skipping over header
            {
                var foodObject = new Object();
                foodObject.label = data[i][1];
                foodObject.weight = data[i][2];
                foodObject.servingSize = data[i][3];
                foodObject.calories = data[i][4];
                arrayOfObjects.push(foodObject);
            }
        }
    });

    $('#food').autocomplete({
        source: arrayOfObjects,
        select: function (event, ui) {
            selectedObj = ui.item;
            alert("selected object=" + selectedObj.value);
        },
        minLength: 1
    });
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM