繁体   English   中英

Ajax函数只运行一次

[英]Ajax function runs only once

我正在尝试创建一个从用户那里获取电子邮件标题的网页。 当用户单击按钮分析页面时,会看到代码并从电子邮件的标题中找出源IP地址。 然后,此网页向freegeoip.com查询提取的IP地址数。

这是问题所在。 无论我从电子邮件头中获得多少个ip地址,我的代码只运行一次ajax函数,然后再没有请求。

你可以帮我这个吗?

 var myLatlngArray; function iAnalyse() { //document.getElementById("result").innerHTML //document.getElementById("headerValue").value; var lines = document.getElementById("headerValue").value.split('\\n'); var ipAddrs = []; var cnt=0; for(i=0; i<lines.length; i++) { if(lines[i].startsWith("Received: from")) { ipAddrs[cnt++]=ipAddr=lines[i].substring(lines[i].lastIndexOf("[")+1,lines[i].lastIndexOf("]")); } } myLatlngArray=new Array(cnt); for(j=0;j<cnt;j++) getIPaddress(ipAddrs[j]); //alert(ipAddrs.length); } //http://stackoverflow.com/questions/646628/how-to-check-if-a-string-startswith-another-string if (typeof String.prototype.startsWith != 'function') { // see below for better implementation! String.prototype.startsWith = function (str){ return this.indexOf(str) == 0; }; } var xHRObject = false; if (window.XMLHttpRequest) { xHRObject = new XMLHttpRequest(); } else if (window.ActiveXObject) { xHRObject = new ActiveXObject("Microsoft.XMLHTTP"); } function getIPaddress(ipAddrs) { xHRObject.open("GET", "http://freegeoip.net/json/"+ipAddrs+"?t=" + Math.random(),true); xHRObject.onreadystatechange = getData; xHRObject.send(null); } var aList=0; function getData() { if ((xHRObject.readyState == 4) && (xHRObject.status == 200)) { if (window.XMLHttpRequest) { alert("abc"); //codes here should be run as many as the number of cnt in iAnalyse function, but it is called only once.. var jsonObj = JSON.parse(xHRObject.responseText); myLatlngArray[aList]=new Array(2); myLatlngArray[aList][0]=jsonObj.latitude; myLatlngArray[aList][1]=jsonObj.longitude; aList++; xHRObject = new XMLHttpRequest(); //google.maps.event.addDomListener(window, 'load', initialize()); } } } 
 <!DOCTYPE html> <html> <head> <title>TEST</title> <script src="analyse.js"></script> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <meta charset="utf-8"> <style> html, body, #googleMap { width:1000px; height:500px; } </style> <script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script> </head> <body> <p>IT Security &nbsp;&nbsp;&nbsp;<button onclick="iAnalyse()">Analyse it!</button> </p> <textarea id="headerValue" rows="10" cols="140">Past your email header here.</textarea> <p><div id="googleMap"></div></p> </body> </html> 

您可以使用以下代码将测试电子邮件标头放入textarea。

`Delivered-To: xxxxxxx@gmail.com
Received: by 10.216.7.2 with SMTP id 2csp890396weo;
        Sat, 13 Sep 2014 10:51:53 -0700 (PDT)
X-Received: by 10.236.230.70 with SMTP id i66mr19664921yhq.26.1410630711344;
        Sat, 13 Sep 2014 10:51:51 -0700 (PDT)
Return-Path: <eBay@ebay.com.au>
Received: from iflip4 ([108.166.68.249])
        by mx.google.com with ESMTPS id 24si1044060yhd.26.2014.09.13.10.51.49
        for <multiple recipients>
        (version=TLSv1.2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128);
        Sat, 13 Sep 2014 10:51:51 -0700 (PDT)
Received-SPF: permerror (google.com: permanent error in processing during lookup of eBay@ebay.com.au) client-ip=108.166.68.249;
Authentication-Results: mx.google.com;
       spf=permerror (google.com: permanent error in processing during lookup of eBay@ebay.com.au) smtp.mail=eBay@ebay.com.au;
       dmarc=fail (p=NONE dis=NONE) header.from=ebay.com.au
Message-Id: <54148437.a401ec0a.35e9.ffffe2e6SMTPIN_ADDED_MISSING@mx.google.com>
Received: from [194.1.180.85] (port=12990 helo=User)
  by iflip4 with esmtpa (Exim 4.82)
  (envelope-from <eBay@eBay.com.au>)
  id 1XRT9o-0006MC-PP; Tue, 09 Sep 2014 21:41:02 +0000
From: "PayPal"<eBay@eBay.com.au>
`

你的代码有一些问题,关闭实际上不是一个。 但实际上你有一个xhr请求用于你的所有请求,但是没有用。 您需要为每个请求创建XMLHttpRequest的new实例。 那应该解决它:)

通过在请求函数范围内移动响应处理函数,您可以通过生成的闭包访问原始xhr请求。

(顺便说一句,我不确定我是否正确地将XMLHttpRequest接口规范化为微软“事物”,它基本上只是猜测。)

var myLatlngArray;

function iAnalyse(){
  var lines = document.getElementById("headerValue").value.split('\n');
  var ipAddrs = [];
  var cnt=0;

  for(i=0; i<lines.length; i++){
    if(lines[i].startsWith("Received: from")){
        ipAddrs[cnt++]=ipAddr=lines[i].substring(lines[i].lastIndexOf("[")+1,lines[i].lastIndexOf("]"));
    }
  }
  myLatlngArray=new Array(cnt);
  for(j=0;j<cnt;j++){
    getIPaddress(ipAddrs[j]);
  }
}
if (typeof String.prototype.startsWith != 'function') {
  String.prototype.startsWith = function (str){
    return this.indexOf(str) == 0;
  };
}
window.XMLHttpRequest=XMLHttpRequest||function(){
  return ActiveXObject&&ActiveXObject("Microsoft.XMLHTTP")
};


function getIPaddress(ipAddrs){
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "http://freegeoip.net/json/"+ipAddrs+"?t=" + Math.random(),true);
  xhr.onreadystatechange = getData;
  xhr.send(null);

  function getData(){
    if(xhr.readyState == xhr.DONE && xhr.status == 200){
      var jsonObj = JSON.parse(xhr.responseText);
      myLatlngArray[aList]=new Array(2);
      myLatlngArray[aList][0]=jsonObj.latitude;
      myLatlngArray[aList][1]=jsonObj.longitude;
      aList++;
    }
  }
}

var aList=0;

如果您的网站上有多个AJAX任务,则应创建一个用于创建XMLHttpRequest对象的标准函数,并为每个AJAX任务调用此函数。

http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp

尝试这样的事情:

function createXhr(){
  var xHRObject = false;
  if (window.XMLHttpRequest) {
    xHRObject = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    xHRObject = new ActiveXObject("Microsoft.XMLHTTP");
  }
  return xHrObject;
}

然后你可以:

function getIPaddress(ipAddrs) {
  var xHRObject = createXhr();
  ...
}

和:

function getData(event){
  var xHrObject = event.target;
  ...
}

如果你担心CORS,你可能想尝试这样的事情:

function createCORSRequest(method, url) {
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    // XHR for Chrome/Firefox/Opera/Safari.
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined") {
    // XDomainRequest for IE 9 and earlier.
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
    // CORS not supported.
    xhr = null;
  }
  return xhr;
}

来源: http//docs.webplatform.org/wiki/apis/xhr/XMLHttpRequest

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM