在jquery中创建一个数组并检查它是否是一个元素
使用ajax & 获取一些数据后; json 我有这个函数
if(data.length != 0) {
var arreglo = new Array();
$.each(data, function(index, data) {
if (jQuery.inArray(data.id, arreglo) == -1) {
arreglo.push(data.id);
$("#envivo").append("<li>Titulo: " + data.titulo + " Link: " + data.link + " Fuente: " + data.fuente + "</li>");
}
});
}
}
$(document).ready(function() {
var fecha = Math.round((new Date()).getTime() / 1000);
setInterval(function() {
$.ajax({
data: "fecha="+fecha,
type: "GET",
dataType: "json",
url: "data.php",
success: function(data){
restults(data);
}
});
}, 5000);
});
我想要做什么
- 检查是否从ajax检索到任何数据
- 创建一个数组来存储data.id
- 在来自ajax的数据中循环
- 检查data.id是否在[2]中创建的数组中
- 如果id 它不在数组中,我将其保存到并应用了一些数据
步骤 4
它不起作用,并且是 5 的一部分(保存到数组中)
有什么想法吗?
提前致谢
After getting some data using ajax & json i've got this function
if(data.length != 0) {
var arreglo = new Array();
$.each(data, function(index, data) {
if (jQuery.inArray(data.id, arreglo) == -1) {
arreglo.push(data.id);
$("#envivo").append("<li>Titulo: " + data.titulo + " Link: " + data.link + " Fuente: " + data.fuente + "</li>");
}
});
}
}
$(document).ready(function() {
var fecha = Math.round((new Date()).getTime() / 1000);
setInterval(function() {
$.ajax({
data: "fecha="+fecha,
type: "GET",
dataType: "json",
url: "data.php",
success: function(data){
restults(data);
}
});
}, 5000);
});
What i'm trying to do
- Check if any data it's retrieved from ajax
- Create an array to store data.id
- Loop inside the data from ajax
- Check if data.id it's in array created in [2]
- If id it's not in array, i save it into and apped some data
step 4
it's not working and part of the 5 (saving into array)
Any ideas?
Thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
inArray 函数使用恒等比较运算符 (===)。
如果数据将 id 作为字符串返回,但您将其解释为数字,这将导致问题。
"9" ==== 9 <- 假
"9" == 9 <- 真
The inArray function uses the identity compare operator (===).
This will cause problems if the data returned the id as a string, but you are interpreting is as a number.
"9" ==== 9 <- False
"9" == 9 <- True
我已经尝试过你的代码,它工作得很好:
http://jsfiddle.net/Jfq6d/
你必须检查您获得的数据是否确实符合您的预期。例如,您可以使用 Firefox 中 FireBug 插件中的 Net 选项卡来检查 AJAX 调用中获得的响应。
编辑:
当您想重用该函数时,您必须在函数外部创建数组:
I have tried your code, and it works just fine:
http://jsfiddle.net/Jfq6d/
You have to check that the data that you get actually looks the way that you expect. You can for example use the Net tab in the FireBug addon in Firefox to examine the response that you get in the AJAX call.
Edit:
As you want to reuse the function, you have to create the array outside the function: