jquery - Use a function to set a variable with Javascript? -
i trying use javascript , jquery build html table based on information returned database. have json , database hit working properly, unable show data on page.
this code display data
var temp; var init = function() { $(_getmarketinfo()).appendto(document.body); // used logging temp = $(_getmarketinfo()); console.log(temp); };
and , process data
function _getmarketinfo() { $.ajax({ url:'scripts/db_getmarketinfo.cgi', datatype:'json', success:function(data, teststatus) { var html = ''; html +='<div class="marketinfoholder">'; html +='<table class="tbl" border=1>'; html +=' <tr><th>market information</th></tr>'; html +=' <tr><td>market</td></tr>'; (var i=0;i< data.marketinfo.length; i++){ html += '<tr><td>' + data.marketinfo[i].market_name + '</td></tr>'; } html +='</table>'; html +='</div>'; //used logging console.log(html); return html; }, error:function(data, textstatus) { alert('there error getting market information.'); } }); };
according console logs, html variable have proper html code table, when @ temp variable, logged []. appears that, reason, _getmarketinfo() isn't returning html temp.
i use custom event triggered on success of ajax call.
var init; // bind custom event document // triggered in ajax success callback $(document).bind('init', function (html) { init = html; // used logging console.log(init); }); // run _getmarketinfo in document ready handler // because accessing dom $(document).ready(function () { $(_getmarketinfo()).appendto(document.body); }); // ajax call function function _getmarketinfo() { $.ajax({ url:'scripts/db_getmarketinfo.cgi', datatype:'json', success:function(data, teststatus) { var html = ''; html +='<div class="marketinfoholder">'; html +='<table class="tbl" border=1>'; html +=' <tr><th>market information</th></tr>'; html +=' <tr><td>market</td></tr>'; (var i=0;i< data.marketinfo.length; i++){ html += '<tr><td>' + data.marketinfo[i].market_name + '</td></tr>'; } html +='</table>'; html +='</div>'; // trigger custom event // html used custom parameter; // custom event parameters must passed // in array $(document).trigger('init', [html]); // return html appending return html; }, error:function(data, textstatus) { alert('there error getting market information.'); } }); };
Comments
Post a Comment