简体   繁体   English

Ajax函数只运行一次

[英]Ajax function runs only once

I'm trying to make a web page that gets an email header from user. 我正在尝试创建一个从用户那里获取电子邮件标题的网页。 when a user clicks a button to analyse the page sees the code and finds out source ip addresses from the header of the email. 当用户单击按钮分析页面时,会看到代码并从电子邮件的标题中找出源IP地址。 then this web page queries to freegeoip.com with the number of ip addresses that are extracted. 然后,此网页向freegeoip.com查询提取的IP地址数。

here is the problem. 这是问题所在。 no matter how many ip addresses i got from an email header, my code only runs the ajax function one time, then no requests anymore. 无论我从电子邮件头中获得多少个ip地址,我的代码只运行一次ajax函数,然后再没有请求。

could you help me with this please? 你可以帮我这个吗?

 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> 

You can use the following code for test email header to put in the textarea. 您可以使用以下代码将测试电子邮件标头放入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>
`

Your code had a few problems, the closure actually wasn't one. 你的代码有一些问题,关闭实际上不是一个。 But you actually had a single xhr request you used for all your requests, that doesn't work out. 但实际上你有一个xhr请求用于你的所有请求,但是没有用。 You need to create a new instance of the XMLHttpRequest for every request. 您需要为每个请求创建XMLHttpRequest的new实例。 That should solve it :) 那应该解决它:)

By moving the response handler function in the scope of your request function you can access the original xhr request through the closure generated. 通过在请求函数范围内移动响应处理函数,您可以通过生成的闭包访问原始xhr请求。

(btw I'm not sure if I normalized the XMLHttpRequest Interface correctly for microsofts "thing", it's basically just a guess.) (顺便说一句,我不确定我是否正确地将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;

If you have more than one AJAX task on your website, you should create ONE standard function for creating the XMLHttpRequest object, and call this for each AJAX task. 如果您的网站上有多个AJAX任务,则应创建一个用于创建XMLHttpRequest对象的标准函数,并为每个AJAX任务调用此函数。

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

Try something like this: 尝试这样的事情:

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

and then you can: 然后你可以:

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

and: 和:

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

If you are concerned about CORS, you might want to try something like this: 如果你担心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;
}

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

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

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