当窗口加载时,IP将生成我想在Code Behind page load
JavaScript
<script type="text/javascript">
window.onload = function () {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://api.ipify.org?format=jsonp&callback=DisplayIP";
document.getElementsByTagName("head")[0].appendChild(script);
};
function DisplayIP(response) {
document.getElementById("<%=ipaddress.ClientID%>").innerHTML = "Your IP Address is " + response.ip;
}
</script>
标签
<span id = "ipaddress" runat="server"></span>
代码隐藏文件:
protected void Page_Load(object sender, EventArgs e)
{
MyIP = ipaddress.InnerText;
url = "http://ip-api.com/xml/" + MyIP + "";
}
答案 0 :(得分:0)
ipaddress
不包含预期值的原因是因为Page_Load
事件在执行Javascript之前发生。您可以尝试使用文本框中的TextChanged
事件。
或者,您可以直接在代码隐藏中获取客户端的IP地址,而无需使用javascript(see here)。
以下是建议的解决方案之一(摘自上面的链接):
protected string GetIPAddress()
{
System.Web.HttpContext context = System.Web.HttpContext.Current;
string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (!string.IsNullOrEmpty(ipAddress))
{
string[] addresses = ipAddress.Split(',');
if (addresses.Length != 0)
{
return addresses[0];
}
}
return context.Request.ServerVariables["REMOTE_ADDR"];
}