2011-02-18 65 views
0

我想使用JavaScript和jquery基于从数据库返回的信息构建一个HTML表。我有JSON和数据库正常工作,但我无法在我的页面上显示数据。使用函数使用Javascript设置变量?

这是代码显示的数据

var temp; 

var init = function() { 
    $(_getMarketInfo()).appendTo(document.body); 

    // Used for logging 
    temp = $(_getMarketInfo()); 
    console.log(temp); 
}; 

然后获取和处理数据

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>'; 

      for (var i=0;i< data.marketInfo.length; i++){ 
       html += '<tr><td>' + data.marketInfo[i].market_name + '</td></tr>'; 
      } 

      html +='</table>'; 
      html +='</div>'; 

      //used for logging 
      console.log(html); 

      return html; 
     }, 
     error:function(data, textStatus) { 
      alert('There was an error getting market information.'); 
     } 
    }); 
}; 

据控制台日志,在html变量确实有正确的HTML代码表,但是当我查看temp变量时,它会记录为[]。看起来,由于某种原因,_getMarketInfo()不能正确地将html返回到temp。

回答

0

我会使用ajax调用成功时触发的自定义事件。

var init; 

// bind a custom event to the document that is 
// triggered in your ajax success callback 
$(document).bind('init', function (html) { 
    init = html; 

    // Used for logging 
    console.log(init);  
}); 

// run _getMarketInfo in a document ready handler 
// because you are accessing the DOM 
$(document).ready(function() { 
    $(_getMarketInfo()).appendTo(document.body);  
}); 

// your 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>'; 

      for (var i=0;i< data.marketInfo.length; i++){ 
       html += '<tr><td>' + data.marketInfo[i].market_name + '</td></tr>'; 
      } 

      html +='</table>'; 
      html +='</div>'; 

      // trigger your custom event with 
      // the html used as a custom parameter; 
      // custom event parameters must be passed 
      // in an array 
      $(document).trigger('init', [html]); 

      // return your html for appending 
      return html; 
     }, 
     error:function(data, textStatus) { 
      alert('There was an error getting market information.'); 
     } 
    }); 
}; 
0

由于ajax运行异步,因此无法从成功函数返回。 此外,如果你包装在$()中的东西,他们将成为一个数组,因为这是jQuery的工作方式。

​​

你也可以把在somekind的命名空间的代码,把它清理干净更

+0

我还建议jQuery.tmpl,如果你想更容易构建html – ullmark 2011-02-18 16:39:35

1

刚刚转会成功里面你appendTo逻辑:功能(数据,testStatus){你的Ajax调用

+0

这是比它应该更容易...谢谢! – ThatGuyYouKnow 2011-02-18 19:16:11