本文介绍了当分配给变量时,Request.ServerVariables("..")返回未定义,但是可以通过Response.Write(“.")显示其值.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试检索用户的IP地址并将其分配给变量:

I am trying to retrieve the user's IP address and assign it to a variable:

var ipAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR") ||
                Request.ServerVariables("REMOTE_ADDR") ||
                Request.ServerVariables("HTTP_HOST");

Response.Write(Request.ServerVariables("HTTP_HOST") + "<br />\n\n");    // produces "localhost"
Response.Write(Request.ServerVariables("REMOTE_ADDR") + "<br />\n\n");  // produces "::1"
Response.Write(Request.ServerVariables("HTTP_X_FORWARDED_FOR") + "<br />\n\n"); // produces "undefined"
Response.Write("ipAddress = " + typeof ipAddress + " " + ipAddress + "<br />\n\n");     // produces "ipAddress = object undefined"

我正在将JScript用于Classic ASP.我不确定此时该做什么.有人可以帮忙吗?

I am using JScript for Classic ASP. I am unsure as to what to do at this point. Can anyone help?

谢谢

推荐答案

在使用JScript的ASP中,工作原理与使用VBScript的ASP有所不同.

Things work in ASP with JScript a little bit different than ASP with VBScript.

由于所有内容都是JavaScript中的对象,因此使用var ipAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR")可以获得对象引用而不是字符串值,因为像大多数其他Request集合一样,ServerVariablesIStringList对象的集合

Since everything is an object in JavaScript, with var ipAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR") you get an object reference instead of a string value because like most of other Request collections, the ServerVariables is a collection of IStringList objects

因此,要使短路评估按预期工作,您需要使用值,而不是对象引用.

So, to make that short-circuit evaluation work as you expect, you need to play with the values, not the object references.

如果有值(键存在),则可以使用Item方法返回IStringList对象的字符串值,否则,它会返回在JScript中评估为undefinedEmpty值.

You can use the Item method that returns the string value of IStringList object if there's a value (the key exists), otherwise it returns an Empty value that evaluated as undefined in JScript.

var ipAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR").Item ||
                Request.ServerVariables("REMOTE_ADDR").Item ||
                Request.ServerVariables("HTTP_HOST").Item;

这篇关于当分配给变量时,Request.ServerVariables("..")返回未定义,但是可以通过Response.Write(“.")显示其值.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-12 11:49