我正在为用户创建一个小工具,放在他们的博客上,将流量定向到我的优惠券代码网站。我想要的小工具访问数据库,并输出当天的5大优惠券。以下是我将他们放在他们的网站上的内容:
<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文件,以及如何循环遍历它以输出一个无序列表,每个优惠券都是它自己的列表项?
非常感谢任何帮助!
发布于 2011-09-28 21:38:51
使用Ajax
从widget发送一个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");
}
});https://stackoverflow.com/questions/7582013
复制相似问题