Search code examples
javascriptjqueryajaxjsonace-editor

How use jquery getJSON with a local variable


i want to extend the completions of Ace Editor, and i need a json of word, this is my code:

function load_completions() {

        var object = $('#preview').attr('class');

        $.ajax({
            type: "POST",
            url: "test_editor_ajax.php",
            data: {action:'load_completion', object:object},
            cache: false,
            success: function(json){
                var adminCompleter = {
                    getCompletions: function(editor, session, pos, prefix, callback) {
                        if (prefix.length === 0) { callback(null, []); return }
                        $.getJSON(json, function(wordList) {
                            callback(null, wordList.map(function(ea)  {           
                                return {name: ea.word, value: ea.word, meta: "optional text"}
                            }));
                        })
                    }
                }
                langTools.addCompleter(adminCompleter);
            }
        });

        return false;

    }

the getJSON function require a url to a json file, but i have created the json locally with ajax, how you can see in the above code, the ajax call return a json that i generate in this way:

echo json_encode($completions);

and $completions is an array, so my question is how i can use it in that functions?


Solution

  • JSON is JavaScript Object Notation, so this: [] or {} is JSON.

    I guess you only need:

            getCompletions: function(editor, session, pos, prefix, callback) {
                if (prefix.length === 0) {
                  callback(null, []);
                  return;
                }
                callback(null, wordList.map(function(ea)  {           
                    return {name: ea.word, value: ea.word, meta: "optional text"}
                }));
            }
    

    $.getJSON will call the server using AJAX. It's just a shorthand method for doing a GET request that accepts application/json in a response.