开发者

debug help with rare unexpected output in js

I have the following javascript on my page that is supposed to generate and go to a url instead of posting a form:

var tokenList = ["auto", "usate"];
var dirList = [];

function makeUrl(prov, manuf, model, price){
  if (_addToken(prov)){
    _joinTokens();
  }
  if (_addToken(manuf)){
    _addToken(model);
    _joinTokens();
  }
  if (price){
    return _joinDirs() + "?prezzo=" + price;
  }
  return _joinDirs();
}

function _addToken(tok){
  if (tok){
    tokenList.push(tok.replace(/ /g,"_"));
    return true;
  }
  return false;
}
function _joinTokens(){
  dirList.push(tokenList.join('-'));
  tokenList = [];
}
function _joinDirs(){
  if (tokenList){
    _joinTokens();
  }
  var url = '/' + dirList.join('/');
  if (url.charAt(url.length-1) == '/'){
    url = url.slice(0, -1);
  }
  return url;
}

It's triggered by this code:

$(document).ready(function(){
  $('#navForm').submit(function() {
    var prov = $("[name=select-provincia]").val();
    var manuf = $("[name=select-marca]").val();
    var model = $("[name=select-modello]").val();
    var price = $("[name=select-prezzo]").val();
    var url = makeUrl(prov, manuf, model, price);
    window.location = url;
    return false;
  });
});

It's been a long while since I translated this code from its original python. I've been getting rare errors in my server logs occasionally that show users trying to visit strange urls that look almost like two urls concatenated. I haven't been able to ever duplicate such an error, but my best guess is that there is something going on with my javascript. The last two times I got this error I noticed that the user was using firefox 3.6 and iphone. Could this be some kind of browser incompatibility? Is there anything wrong with my javascript at all? Is the error just in userland?

For reference here is an example wrong ur开发者_如何学JAVAl:

/auto-usate-pesaro_e_urbino/fiat-500//rimini/fiat-500?prezzo=13000

and two possible correct ones:

/auto-usate-pesaro_e_urbino/fiat-500?prezzo=13000

/auto-usate-rimini/fiat-500?prezzo=13000

Any unrelated suggestions for optimizing the code are welcome since I am bad at this.


Not sure it that's the case, but I think those strange URLs might be a result of appending the generated URL to the URL of the page being viewed. You are generating just the pathname part of the URL, not including the protocol and host name (http://foo.com) -- it's possible that some browsers are interpreting this path as relative to the current one. Try prepending the URL with the protocol and hostname.

You might also want to see this answer: Setting JavaScript window.location and follow the advice to write the URL to window.location.href.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜