Autocomplete (jQuery UI) and localstorage

2019-03-31 13:18发布

问题:

I just get a strange bug when using those two tools. I'm making an AJAX query to an API, then retrieving JSON data which is stored within localStorage and displayed into an autocomplete panel. The problem is that according to the origin of the autocomplete source, the panel will react differently.

Here is the callback function called on AJAX success :

function _company_names(data)
{
    localStorage.setItem('ac_source', JSON.parse(data).Result);

    // Works fine
    $("#search_input").autocomplete( "option", "source", JSON.parse(data).Result);
    // Send an AJAX request
    $("#search_input").autocomplete( "option", "source", localStorage.getItem('ac_source'));
}

If i pass JSON.parse(data).Result as result to the autocomplete source, it will be fine. However if I pass localStorage.getItem('ac_source'), the ac widget will send an AJAX request (not using my own function) blowing in the wind (my node.js will try to parse it, etc.).

I'm using localstorage to access these data from an other part of my code (store it to compare with other user research and displaying it if the request is the same).

回答1:

You can store only string data in Local Storage:

localStorage.setItem('ac_source', '{"key":"data","key1":"data1"}');

$("#search_input").autocomplete( "option", "source", JSON.parse(localStorage.getItem('ac_source')).Result);