我该如何改进这个Ajax脚本?

时间:2011-04-09 20:55:46

标签: ajax security

我已经为管理员编写了PHP和javascript的组合,可以在没有页面重新加载的情况下无缝地为用户提供分数。这是我第一次真正使用Ajax,所以我想要一些改进代码的技巧。我怎样才能使它更安全/更有效?顺便说一句,这段代码在html源代码中可见。

P.S:如果有关于此类事情的最佳做法,请告诉我并发布您对该主题的任何链接。

// First pass: add the points
function addBonus()
{
  document.getElementById('response').innerHTML = '<img src=images/loading2.gif></img>'; // Show that process is taking place
  var xmlHttp = getXMLHttp();

  xmlHttp.onreadystatechange = function()
  {
    if(xmlHttp.readyState == 4)
    {
      verifyPoints(); // Check if points have actually been given
    }
  }
 // Generated by templating system
 // Triggers call to PHP page that gives bonus points to user
   var url="page.php?id=2&a=bonus"; 


  xmlHttp.open("GET", url, true);
  xmlHttp.send(null);
}

// Second pass: check the points have been given
function verifyPoints(){
  var xmlHttp = getXMLHttp();

  xmlHttp.onreadystatechange = function()
  {
    if(xmlHttp.readyState == 4)
    {
      HandleResponse(xmlHttp.responseText );
    }
  }

  url="GetPoints.php?i=2"; // Generated by templating system

  xmlHttp.open("GET", url, true);
  xmlHttp.send(null);
}

function HandleResponse( response )
{
    var oldPoints = parseInt(document.getElementById('numPoints').innerHTML);
    var currentPoints = parseInt(response);

    if( currentPoints == (oldPoints + 150) ){
        document.getElementById('response').innerHTML = '<img src=images/tick.png></img>'; // Bonus points added: show tick icon
    } else {
        document.getElementById('response').innerHTML = '<img src=images/cross.png></img>'; // Bonus points not added: show red cross icon
    }

    document.getElementById('numPoints').innerHTML = currentPoints; // Update points display
}

1 个答案:

答案 0 :(得分:1)

page.php?id=2&a=bonus如何知道真正的管理员才能获得奖励积分?

你有没有想过XSRF?换句话说,用户可以在他们的网站上放置一些东西,这样如果管理员访问它,在登录时,会发送一个请求,其中包含管理员的cookie,无意中会产生积分。

您不应该使用GET请求来更改内容,例如分配点。 来自http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

  

实施者应该意识到软件代表用户通过互联网进行交互,并且应该小心让用户了解他们可能采取的任何可能对他们自己或他人有意外意义的行为。

     

特别是,已经确定了GET和HEAD方法不具有采取除检索之外的动作的重要性的约定。这些方法应该被认为是“安全的”。这允许用户代理以特殊方式表示其他方法,例如POST,PUT和DELETE,以便让用户知道正在请求可能不安全的操作。

导致服务器状态更改的任何内容都应使用其中一种非幂等HTTP方法。可能是POST。顺便说一句,幂等操作是在重新应用于其输出时产生相同的操作的操作。因此f等等f(x) == f(f(x)) == f(f(f(x))是幂等的。{/ 1>

最后

url="GetPoints.php?i=2"

正在设置一个全局变量。您可能希望前面有var