Javascript函数检查vb变量

时间:2011-11-09 12:39:47

标签: javascript

我正在使用以下功能,但确实有效,有人可以指出错误。

vb变量是从数据库查询中生成的。

window.onload function PostCodeChecker() {
if (<%= sPostalCode %> !== 'SW') {
alert("This is not an SW Postal Code");
}
}

4 个答案:

答案 0 :(得分:2)

这里真正发生的是您的服务器端代码正在交换您放置<%= sPostalCode %>的值,并将结果发送到浏览器。因此,如果sPostalCode是(比方说)“NW10”,那么你就得到了

window.onload function PostCodeChecker() {
if (NW10 !== 'SW') {
//  ^--- ERROR (unless you happen to have a client-side variable by that name, which I'm guessing you don't)
alert("This is not an SW Postal Code");
}
}

因此,您需要引用它(并且您需要添加缺少的=),如下所示:

//            v-- was missing
window.onload = function PostCodeChecker() {
if ('<%= sPostalCode %>' !== 'SW') {
//  ^--- here          ^--- and here
alert("This is not an SW Postal Code");
}
}

...所以浏览器的内容是:

window.onload = function PostCodeChecker() {
if ('NW10' !== 'SW') {
alert("This is not an SW Postal Code");
}
}

假设字符串中不包含任何'个字符,或者在无效的JavaScript字符串中产生的其他字符(当服务器端处理完成并且结果发送到浏览器时)文字。

当然,你可以这样做:

<% If sPostalCode <> "SW" Then %>
window.onload = function() {
alert("This is not an SW Postal Code");
}
<% End If %>

...因为它是服务器端变量,所以你可以在服务器端进行测试。


旁注:这种表达形式:

something = function name() { ... };

...在各种浏览器上都有问题,最明显的是IE。它被称为命名函数表达式,因为它是一个函数表达式,其中函数具有名称(在本例中为name)。在IE上,它会导致创建两个完全独立的函数,这可能会让人感到困惑。更多:Double-take

答案 1 :(得分:2)

首先出错的是:

window.onload function PostCodeChecker() {

您缺少赋值运算符并为其命名(IE IRRC中的内存泄漏):

window.onload = function () {

第二件事是错误的:

if (<%= sPostalCode %> !== 'SW') {

可能会输出类似

的内容
if (SW !== 'SW') {

SW是未定义的值。您可能希望将ASP包装在引号中,并确保输出的内容是JS和HTML安全。

最重要的是你在客户端上进行测试,当你在服务器上轻松地进行测试时。

Psuedo-code 因为我不做ASP:

<% if (sPostalCode == "SW") {
       print 'alert("This is not an SW Postal Code");'; 
   }
%>

(但完全从JS中取出它并将其作为文本放在页面中是通常的,最可靠的方法)。

答案 2 :(得分:0)

如果没有引号,它将寻找一个名称为sPostalCode值的变量

尝试:

window.onload = function PostCodeChecker() {
    if ('<%= sPostalCode %>' !== 'SW') {
        alert("This is not an SW Postal Code");
    }
}

答案 3 :(得分:0)

两个问题。

  1. 您忘记了=,因此您的语法无效。

  2. 在ASP完成其工作后,您应该考虑结果 Javascript的样子。 sPostalCode正在替换,所以如果它的值为“SW”,那么您的条件就会像这样结束:

    if (SW !== 'SW')
    

    这不是有效的Javascript,因为该字符串周围没有引号。

  3. 修复:

    window.onload = function PostCodeChecker() { // <---- equals
       if ('<%= sPostalCode %>' !== 'SW') {         // <---- quotes in the JS
          alert("This is not an SW Postal Code");
       }
    }
    

    ^我还添加了缩进以使您的代码更清晰。我强烈建议你一直这样做。

    sPostalCode包含任何会破坏Javascript语法的字符时,您还应该考虑会发生什么。例如,'。你应该相应地准备或“转义”ASP中的变量。