Answer the question
In order to leave comments, you need to log in
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);
};
var btn = $('<button type="button"></button>');
btn.setLanguage({text:'login_error'});
$('body').append(btn);
$.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>');
Answer the question
In order to leave comments, you need to log in
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);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question