English 中文(简体)
在JavaScript中将用户输入编码为URL GET参数
原标题:Encoding user input as URL GET parameter in JavaScript

我正在编写一个JavaScript函数,该函数需要维护三个属性:

  • be very small and lightweight - no external libraries
  • encode a string in such a way as to be able to be passed as a GET parameter
  • this string must be decoded again at its destination

实际上,它通过将用户的用户名和密码发送到PHP页面来验证用户。这是通过GET完成的,因为我还没有找到后台跨域POST请求的方法。问题是,如果用户的密码中有#或类似的字符,则无法正确发送。

目前为了避免这种情况,我<code>encode()</code>在发送密码字符串之前先发送密码字符串,这样就可以毫无问题地接收密码。然而,我读到PHP的urldecode()并不是一个完美的模拟,因为有些角落的情况会有不同的处理(即+等)。遗憾的是,我再也找不到这份文件了,所以我不能引用它,但要点是其中一个将空格转换为+号,另一个将其视为实际的加号或类似的东西。。。

因此,我正在寻找一个Javascript函数,它可以获取字符串并使其URL安全,并且在PHP中具有完美的反转功能,以便可以恢复原始字符串。

我目前用来实现这一点的代码可能很糟糕:

login.onsubmit = function(){
    loginFailMsg.style.display =  none ;
    var inputs = login.getElementsByTagName( input );
    var formdata = 
         username= +inputs[0].value+ &password= +encode(inputs[1].value);
    submit.src = formtarget+ /auth/bklt? +formdata;
    userinfo = undefined;
    setTimeout(getUserinfo,300);
    return false;
};
最佳回答
 &password= +encode(inputs[1].value)

encode函数来自哪里?在我看来,你的问题的快速答案是使用encodeURIComponent(),自JavaScript 1.5起可用。另请参阅比较escape()、encodeURI()和encodeURIComponent();它也不会对所有内容进行编码,但会对服务器期望的所有内容进行编码。

(至于跨域AJAX POST调用,我真的会看看“JSON with Padding”。请参阅JSONP与jQuery,我在前面的评论中提到了这一点。这也将防止您随机选择的超时出现问题,jQuery还将帮助您,很多,消除输入[0].value等。而且,当您显然服务器上已经有了MD5哈希,我真的会对密码客户端进行哈希——请参阅Karl的答案——然后比较这些哈希。尊重用户的密码和自己的时间,放弃没有外部库的要求!)

问题回答

encodeURIComponent,PHP将在填充$_POST$_GET时自动对其进行解码

我不认为存在可逆散列函数这样的东西。有很多javascript md5库可用。





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签