Javascript 在不打开新页面的情况下从浏览器调用客户端 URL

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26555848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:02:06  来源:igfitidea点击:

Calling client side URL from browser without opening new page

javascripthtmlasp.netclient-side

提问by samhankin

I'm trying to create a button that will dial an IP Phone by visiting a URL string:

我正在尝试创建一个按钮,通过访问 URL 字符串来拨打 IP 电话:

http://admin:[email protected]/cgi-bin/ConfigManApp.com?Id=34&Command=1&Number=0123456789

When entering directly into the browser, the page returns a 1 and dials the IP phone.

直接进入浏览器,页面返回1,拨打IP电话。

On my website I can create a simple link that when clicked, visits this page in a new window.

在我的网站上,我可以创建一个简单的链接,单击该链接后,会在新窗口中访问此页面。

Is there any way of visiting this page without the user seeing that it opens?

是否有任何方法可以访问此页面而不会让用户看到它已打开?

回答by Dave

Sure you can use an AJAX call:

当然你可以使用 AJAX 调用:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
  if (xmlhttp.readyState==4 && xmlhttp.status==200) {
    var response = xmlhttp.responseText; //if you need to do something with the returned value
  }
}

xmlhttp.open("GET","http://admin:[email protected]/cgi-bin/ConfigManApp.com?Id=34&Command=1&Number=0123456789",true);
xmlhttp.send();

jQuerymakes this even easier:

jQuery使这更容易:

$.get("http://admin:[email protected]/cgi-bin/ConfigManApp.com?Id=34&Command=1&Number=0123456789")

Edit: since you are traveling across domains and can't use CORS, you can open the link using javascript and them immediately close the window. Example below:

编辑:由于您跨域旅行并且不能使用 CORS,您可以使用 javascript 打开链接,然后他们立即关闭窗口。下面的例子:

document.getElementById("target").onclick = function(e) {
    var wnd = window.open("http://admin:[email protected]/cgi-bin/ConfigManApp.com?Id=34&Command=1&Number=0123456789");
    wnd.close();
    e.preventDefault();
};

回答by Travis J

You would use an XMLHttpRequest

您将使用XMLHttpRequest

function dialResponse() {
 console.log(this.responseText);//should be return value of 1
}

var oReq = new XMLHttpRequest();
oReq.onload = dialResponse;
oReq.open("get", "http://admin:[email protected]/cgi-bin/ConfigManApp.com?Id=34&Command=1&Number=0123456789", true);
oReq.send();

This will be semi-hidden. However, it is still issued client side so they will see it occur in the network record. If you want this to be truly hidden, you would have to do it server side.

这将是半隐藏的。但是,它仍然在客户端发出,因此他们会在网络记录中看到它。如果您希望真正隐藏它,则必须在服务器端进行。