我正在尝试检索用户的IP地址并将其分配给一个变量:
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 for Classic ASP。在这一点上,我不确定该怎么做。有人能帮上忙吗?
谢谢
发布于 2020-09-06 02:33:02
使用JScript的ASP和使用VBScript的ASP有一点不同。
因为在JavaScript中一切都是对象,所以使用var ipAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR")
可以获得对象引用而不是字符串值,因为与大多数其他Request
集合一样,ServerVariables
是IStringList
对象的集合
因此,要使短路求值像您所期望的那样工作,您需要处理值,而不是对象引用。
如果存在值(键存在),则可以使用Item
方法返回IStringList
对象的字符串值,否则返回一个Empty
值,该值在JScript中的计算结果为undefined
。
var ipAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR").Item ||
Request.ServerVariables("REMOTE_ADDR").Item ||
Request.ServerVariables("HTTP_HOST").Item;
发布于 2020-09-06 00:52:53
我解决了获取IP地址的问题,JScript的真假是一场彻头彻尾的噩梦。
if (!String.prototype.isNullOrEmpty) {
String.isNullOrEmpty = function(value) {
return (typeof value === 'undefined' || value == null || value.length == undefined || value.length == 0);
};
}
var ipAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR") ||
Request.ServerVariables("REMOTE_ADDR") ||
Request.ServerVariables("HTTP_HOST");
function getIPAddress() {
try {
if (String.isNullOrEmpty(ipAddress)) {
ipAddress = Request.ServerVariables("HTTP_X_FORWARDED_FOR");
}
if (String.isNullOrEmpty(ipAddress)) {
ipAddress = Request.ServerVariables("REMOTE_ADDR");
}
if (String.isNullOrEmpty(ipAddress)) {
ipAddress = Request.ServerVariables("HTTP_HOST");
}
} catch (e) {
Response.Write("From getIPAddress(): " + e.message);
hasErrors = true;
} finally {
return ipAddress;
}
}
ipAddress = getIPAddress();
Response.Write("ipAddress = " + typeof ipAddress + " " + ipAddress + "<br />\n\n"); // produces "object localhost"
https://stackoverflow.com/questions/63748751
复制相似问题