I
I
Ivan Kashmir2015-08-10 17:58:33
JavaScript
Ivan Kashmir, 2015-08-10 17:58:33

How to correctly generate HTML with text from json?

There is a function that, through ajax, gets the text from json and inserts it into some object

$.fn.setLanguage = function(options){

        options = $.extend({
            language: 'ru',
            text: this.attr('data-text')
        }, options);

        var make = function(){
            var el = $(this);
            $.ajax({
                url : options.language +'.json',
                dataType: 'json',
                success:function(data) {
                    el.html(data[options.text]);
                }
            });
        };

        return this.each(make);
    };

Insert itself:
var btn = $('<button type="button"></button>');
    btn.setLanguage({text:'login_error'});
    $('body').append(btn);

But this is inconvenient, because in the same button there may be some other elements and it is not known where to insert the text.
Decided to do something like this:
$.getText = function(){
        var result;
        $.ajax({
            url :  'text.json',
            async: false,
            dataType: 'json',
            success:function(data) {
                result = data;
            }
        });
        return result
    };

var btn = $('<button type="button">'+ $.getTextFromJson('login_error') +'</button>');

But here everything is done through a synchronous request, which is not very good.
Has anyone done this, please share your solution.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2015-08-10
@Kashmir2606

I would implement something like this.

$.fn.setLanguage = function (options) {
    options = $.extend({
        language: 'ru',
        text: this.attr('data-text')
    }, options);

    var make = function () {
        var el = $(this);
        $.ajax({
            url: options.language + '.json',
            dataType: 'json',
            success: function (data) {
                var html = data[options.text];

                if ($.isFunction(options.callback)) {
                    options.callback(html);
                } else {
                    el.html(html);
                }
            }
        });
    };

    return this.each(make);
};

var wrapper = $('<div><i>Blah</i> <span>replaced</span> <b>Blah</b></div>');

wrapper.setLanguage({
    text: 'login_error',
    callback: $.proxy(function (html) {
        $(this).find('span').html(html);
    }, wrapper),
});

$('body').append(wrapper);

Better yet, of course, make your own event and listen to it.
Well, in general, you can not make an ajax request. It's easier to get the translations object at the start of the page once and work further with it. Then there will be no problem of asynchrony.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question