这听起来很简单,但不知何故它不起作用。
我有一个模板页面,应该使用长轮询来更新。我有长轮询工作,但我在处理/插入数据时失败。
这是 HTML 部分:
<p><b><div id="weather">weather here</div></b></p>
<p><div id="temperature">temperature here</div></p>
<p><i><div id="color">color here</div></i></p>
这是脚本:
var obj = {
"color": "#880000",
"temperature": "hot",
"weather": "cloudy"
};
$.each(obj function (key,value) {
('#key').html('value');
});
此外,我想在样式表中使用颜色,但不知道如何替换非div元素:
#color {
color: #880000
}
我认为每个数组迭代都来自教科书。我错过了什么?(此处为 jfsiddle 示例)
根据建议的第二次尝试,现在更大的图景给出了类型错误:
php 文件(array_2.php):
<?php
/*
Values get read from files.
Here, in the example, we simply populate variables.
Original:
$color = file_get_contents('/path/to/txt/file/with/value');
*/
$color = "#880000";
$temperature = "hot";
$weather = "cloudy";
$items = array(array(id => 'weather', text => $weather), array(id => 'color', text => $color), array(id => 'temperature', text => $temperature),);
echo json_encode($items);
?>
html/javascript:
<html>
<head>
<title>Satus Poller</title>
<script type="text/javascript" src="/jquery.js"></script>
<meta charset="utf-8">
<script type="text/javascript" charset="utf-8">
function addstatus(obj){
$.each(obj, function (key,value) {
$('#' + value.id).html(value.text);
});
};
function waitForMsg(){
$.ajax({
type: "GET",
url: "array_2.php",
async: true,
cache: false,
timeout:50000,
success: function(data){
var arr = $.parseJSON(data);
var obj = arr + ""; /* This doesn't help */
addstatus(obj);
setTimeout(
waitForMsg,
1000
);
},
error: function(XMLHttpRequest, textStatus, errorThrown){
addmsg("error", textStatus + " (" + errorThrown + ")");
setTimeout(
waitForMsg,
15000);
}
});
};
$(document).ready(function(){
waitForMsg();
});
</script>
</head>
<body>
<p><div id="color">color</div></p>
<p><div id="temperature">temperature</div></p>
<p><div id="weather">weather</div></p>
</body>
</html>
(我什至没有尝试同时替换文本和 CSS 元素。)