setTimeout并单击

时间:2010-08-03 09:04:54

标签: javascript jquery ajax settimeout

$(document).ready(function() {
    $(".rshownews").click(function() {
        window.setInterval(function() {ajaxselectrss($(this).attr("title"))}, 1000);
    });
});

 function ajaxselectrss(rssurlvar) {
  var ajaxRequest;  // The variable that makes Ajax possible!

 try{
  // Opera 8.0+, Firefox, Safari
  ajaxRequest = new XMLHttpRequest();
 } catch (e){
  // Internet Explorer Browsers
  try{
   ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
  } catch (e) {
   try{
    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
   } catch (e){
    // Something went wrong
    alert("Your browser broke!");
    return false;
   }
  }
 }
 // Create a function that will receive data sent from the server
 ajaxRequest.onreadystatechange = function(){
  if(ajaxRequest.readyState == 4){

   var ajaxDisplay = document.getElementById('news');
   ajaxDisplay.innerHTML = ajaxRequest.responseText;
  }
 }



 //var rssurlvar = $(this).attr("title");
 var queryString = "rurl=" + rssurlvar;
 var urltofile = "rssget.php";
 ajaxRequest.open("POST", urltofile, true);
 ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 ajaxRequest.setRequestHeader("Content-length", queryString.length);
 ajaxRequest.setRequestHeader("Connection", "close");
 ajaxRequest.send(queryString); 

}

但POST查询未定义。为什么?

4 个答案:

答案 0 :(得分:6)

您的代码至少应如下所示:

$(document).ready(function() {
 $(".rshownews").click(ajaxselectrss);
});

function ajaxselectrss() {
  //ajax function
}

setTimeout(ajaxselectrss, 1000);

对于重复的任务,请改用setInterval

答案 1 :(得分:1)

也许你应该使用setInterval而不是setTimeout

答案 2 :(得分:1)

你不能在setInterval中使用$(this),也许这样的东西会起作用

var rshownews;
function someFunc(rssurlvar) {
  $('body').append('<br>'+rssurlvar);
}
$(document).ready(function() {
    $(".rshownews").click(function() {
        rshownews = $(this).attr("title");
        window.setInterval('someFunc(rshownews)',1000);
    });
});​

使用setInterval进行编辑,您需要将var和函数放在全局范围内,demo

答案 3 :(得分:1)

setInterval可以使用字符串或函数指针。传递包含'$(this)'的字符串将不起作用(因为传递字符串会影响字符串在调用时被评估)。

所以试试:

var title = $(this).attr('title');
setInterval(function() {someFunc(title);}, 1000);
相关问题