MagicSuggest dynamic ajax source

眉间皱痕 提交于 2019-12-22 09:57:10

问题


I'm using MagicSuggest for auto completing an input text, the autocomplete feed its very big so i cant download it complete, in their example they provide this code:

JAVASCRIPT

    $(document).ready(function() {
        var jsonData = [];
        var cities = 'New York,Los Angeles,Chicago,Houston,Paris,Marseille,Toulouse,Lyon,Bordeaux,Philadelphia,Phoenix,San Antonio,San Diego,Dallas,San Jose,Jacksonville'.split(',');
        for(var i=0;i<cities.length;i++) jsonData.push({id:i,name:cities[i],status:i%2?'Already Visited':'Planned for visit',coolness:Math.floor(Math.random() * 10) + 1});

        $('#ms3').magicSuggest({
            selectionPosition: 'bottom',
            renderer: function(city){
                return '<div>' +
                        '<div style="font-family: Arial; font-weight: bold">' + city.name + '</div>' +
                        '<div>Cooooolness: ' + city.coolness + '</div>' +
                       '</div>';
            },
            minChars: 1,
            selectionStacked: true,
            data: jsonData
        });

HTML

<h3>Stacking in bottom, ajax source (type 1 char to load)</h3>
<input id="ms3" style="width:400px;" type="text"/>

If you like, here is a JSFIDDLE. This is working great, but again, the data is complete loaded (in this case hardcoded), is there a way to load the data over ajax based on the user input (each time it changes)? I don't care about the php side since im very capable on that side, but in the front end im very new.


回答1:


The data parameter can take a url to load up elements. From the docs:

data: array / string

JSON Data source used to populate the combo box. 3 options are available here:
No Data Source (default)
When left null, the combo box will not suggest anything. It can still enable the user to enter multiple entries if allowFreeEntries is set to true (default).

Static Source
You can pass an array of JSON objects, an array of strings or even a single CSV string as the data source.
For ex. data: [{id:0,name:"Paris"}, {id: 1, name: "New York"}]

Url
You can pass the url from which the component will fetch its JSON data.
Data will be fetched using a POST ajax request that will include the entered text as 'query' parameter. The results fetched from the server can be: 
- an array of JSON objects (ex: [{id:...,name:...},{...}])
- a string containing an array of JSON objects ready to be parsed (ex: "[{id:...,name:...},{...}]")
- a JSON object whose data will be contained in the results property (ex: {results: [{id:...,name:...},{...}]

By default it will perform a POST query but you can change that with the method parameter. Also by default everytime you hit a key it triggers the query with what the user has typed in as the "query" parameter for the request.

So... First of all here is how you load up data from the server:

$(document).ready(function() {
    $('#ms3').magicSuggest({
        data: 'http://yoururl/data.php'
    });

and then in data.php for example:

<?php

$data = array(array("id"=> 1, "name"=> "New York", "country"=> "United States"),
    array("id"=> 2, "name"=> "Los Angeles", "country"=> "United States"),
    array("id"=> 3, "name"=> "Chicago", "country"=> "United States"),
    array("id"=> 4, "name"=> "Houston", "country"=> "United States"),
    array("id"=> 5, "name"=> "Philadelphia", "country"=> "United States"),
    array("id"=> 6, "name"=> "Paris", "country"=> "France"),
    array("id"=> 7, "name"=> "Marseille", "country"=> "France"),
    array("id"=> 8, "name"=> "Toulouse", "country"=> "France"),
    array("id"=> 9, "name"=> "Lyon", "country"=> "France"),
    array("id"=> 10, "name"=> "Bordeaux", "country"=> "France"),
    array("id"=> 11, "name"=> "Montpellier", "country"=> "France"),
    array("id"=> 16, "name"=> "Phoenix", "country"=> "United States"),
    array("id"=> 17, "name"=> "San Antonio", "country"=> "United States"),
    array("id"=> 18, "name"=> "San Diego", "country"=> "United States"),
    array("id"=> 19, "name"=> "Dallas", "country"=> "United States"),
    array("id"=> 20, "name"=> "San Jose", "country"=> "United States"),
    array("id"=> 21, "name"=> "Jacksonville", "country"=> "United States"));

echo json_encode($data);

?>

Now everytime you hit a key it will perform that query and you can get whatever the user typed by fetching $_POST['query'] within your PHP code. You can then filter the data or perform a DB query or whatever.

Cheers




回答2:


I am doin the same thing, but for some reason the magicsuggest executes the url in endless loop I am using the 1.2.8 version of magicsuggest; i am calling this function from the document onload.

function createMultiSuggest(json){

var jsonData="";

var strTrUserId  = $("#TrUserId").val();
var strUrl='/loadAll.jsp';

_suggest=$("#pcpSuggest,#providerSuggest").magicSuggest({
    //resultAsString: true,
    dataUrlParams: {"action":"fetchData","providerType":"providers","pid":strId,"ms": new Date().getTime()},
    minChars: 2,
    displayField: 'fullname',
    selectionStacked: false,
    data: strUrl,
    typeDelay:400
});
return false;

}



来源:https://stackoverflow.com/questions/15488053/magicsuggest-dynamic-ajax-source

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!