2011-09-28 75 views
0

我正在为用户在其博客上放置一个小部件,以将流量引导至我的优惠券代码网站。我希望小部件访问数据库并输出当天的5张优惠券。以下是我将他们在其网站上放置:如何在javascript小部件中使用Mysql数据库数据

<script src="http://example.com/widget/script.js" type="text/javascript"></script> 
<div id="example-widget-container"></div> 

现在的script.js文件看起来像:

(function() { 

// Localize jQuery variable 
var jQuery; 

/******** Load jQuery if not present *********/ 
if (window.jQuery === undefined || window.jQuery.fn.jquery !== '1.4.2') { 
    var script_tag = document.createElement('script'); 
    script_tag.setAttribute("type","text/javascript"); 
    script_tag.setAttribute("src", 
     "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"); 
    script_tag.onload = scriptLoadHandler; 
    script_tag.onreadystatechange = function() { // Same thing but for IE 
     if (this.readyState == 'complete' || this.readyState == 'loaded') { 
      scriptLoadHandler(); 
     } 
    }; 
    // Try to find the head, otherwise default to the documentElement 
    (document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag); 
} else { 
    // The jQuery version on the window is the one we want to use 
    jQuery = window.jQuery; 
    main(); 
} 

/******** Called once jQuery has loaded ******/ 
function scriptLoadHandler() { 
    // Restore $ and window.jQuery to their previous values and store the 
    // new jQuery in our local jQuery variable 
    jQuery = window.jQuery.noConflict(true); 
    // Call our main function 
    main(); 
} 

/******** Our main function ********/ 
function main() { 
    jQuery(document).ready(function($) { 
     /******* Load CSS *******/ 
     var css_link = $("<link>", { 
      rel: "stylesheet", 
      type: "text/css", 
      href: "style.css" 
     }); 
     css_link.appendTo('head');   

     /******* Load HTML *******/ 
     var jsonp_url = "http://www.mydomain.com/widget_data.php"; 
     $.getJSON(jsonp_url, function(data) { 
      $('#example-widget-container').html("This data comes from another server: " + data.html); 
     }); 
    }); 
} 

})(); // We call our anonymous function immediately 

我遇到的问题是我如何返回一个JSON数组的js文件,以及如何循环输出无序列表,每个优惠券都是自己的列表项目?

任何帮助非常感谢!

回答

0

使用Ajax,

从窗口小部件发送的HttpRequest到web服务器, 从服务器返回一个JSON响应,例如PHP会是这样的

... 
//access the database 
$sql = "SELECT * FROM coupons LIMIT 5"; 
while ($row = mysql_fetch_assoc($sql)) {  
    $coupons[] = $row; 
} 

//return json object 
echo json_encode($coupons); 
... 

一旦JS窗口小部件已收到JSON字符串,可以将其转换成JS对象你需要

JSON.parse(strJSON) 

jQuery的Ajax请求例如什么:

$.ajax({ 
    url: "test.html", 
    context: document.body, 
    success: function(){ 
    $(this).addClass("done"); 
    } 
}); 
+0

你能告诉我如何使ajax请求?我最初使用jQuery和.getJSON函数,但我真的不喜欢它。谢谢! – PaperChase

+0

在jQuery文档中添加了一个jQuery示例 –

+0

检查jquery文档 - > http://api.jquery.com/jQuery.ajax/ –

相关问题