在jQuery中使用数组填充页面
这听起来很简单,但不知怎的它不起作用 我有一个模板页面,应该使用长轮询进行更新。我的轮询时间很长,但在处理/插入数据时失败 这是HTML部分:在jQuery中使用数组填充页面,jquery,arrays,each,Jquery,Arrays,Each,这听起来很简单,但不知怎的它不起作用 我有一个模板页面,应该使用长轮询进行更新。我的轮询时间很长,但在处理/插入数据时失败 这是HTML部分: <p><b><div id="weather">weather here</div></b></p> <p><div id="temperature">temperature here</div></p> <p><i&
<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>
此外,我想在样式表中使用颜色,但我不知道如何替换非分割元素:
#color {
color: #880000
}
我认为每个数组迭代都是从教科书中获得的。我错过了什么?
()
第二次尝试根据建议,现在出现一个类型错误的大图: php文件(array_2.php):
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>
海狸
功能添加状态(obj){
$。每个(对象、功能(键、值){
$('#'+value.id).html(value.text);
});
};
函数waitForMsg(){
$.ajax({
键入:“获取”,
url:“array_2.php”,
async:true,
cache:false,
超时:50000,
成功:功能(数据){
var arr=$.parseJSON(数据);
var obj=arr+“”;/*这没有帮助*/
addstatus(obj);
设置超时(
waitForMsg,
1000
);
},
错误:函数(XMLHttpRequest、textStatus、errorshown){
addmsg(“错误”,textStatus+”(“+errorSprown+”));
设置超时(
waitForMsg,
15000);
}
});
};
$(文档).ready(函数(){
waitForMsg();
});
颜色
温度
天气
(我甚至没有尝试同时替换文本和CSS元素。)OP的方法是正确的,但有几个打字错误
var obj = {
"color": "#880000",
"temperature": "hot",
"weather": "cloudy"
};
// missing $, or jQuery
$.each(obj, function (key,value) {
// missing comma
$('#'+key).html(value);
// variable key and value wrapped inside quote
});
我把它改成了一个数组,这样它就可以用方括号[]表示
var obj = [
{id:"color", text:"#880000"},
{id:"temperature", text:"hot"},
{id:"weather", text: "cloudy"}
];
您缺少对象、函数
旁边的逗号,缺少jquery选择器$“#key”
只是字符串,javascript不知道您指的是变量:
$.each(obj, function (key,value) {
$('#' + value.id).html(value.text);
});
我不认为obj一定是数组。。。它的内容是用来填充一个模板的,我想(因为使用css id)在页面中不会重复。我还不确定它可能实际使用了页面中多个位置的数据。在我更详细的脚本中使用这种方法时,我似乎遇到了冲突:“TypeError:invalid'in'Operator obj”。我需要让它休息一下,然后四处寻找解决方案。@Pienthusist如果您不显示完整的代码,我将无能为力。解决了我的上一个问题。解决方案是将PHP部件提供的数据声明为内容类型:*/json:
header('content-type:application/json')代码>我有一个后续问题。
var obj = [
{id:"color", text:"#880000"},
{id:"temperature", text:"hot"},
{id:"weather", text: "cloudy"}
];
$.each(obj, function (key,value) {
$('#' + value.id).html(value.text);
});