简体   繁体   English

Javascript函数可打开多个链接(如果存在)

[英]Javascript function that opens more than one link (if it exists)

I am looking for a solution to the following scenario: 我正在寻找以下情况的解决方案:

I'd like to write a script that opens a new window with a specified link (ex: http://yadayada.org/customer#.pdf ). 我想编写一个脚本,使用指定的链接打开一个新窗口(例如:http: http://yadayada.org/customer#.pdf )。 With the same function (or click) I'd like to to also open http://yadayada.org/customer#A.pdf if it exists. 使用相同的功能(或单击),我还要打开http://yadayada.org/customer#A.pdf如果存在)。 Below I have a working sample of a function that works to open the files in 2 new windows. 下面有一个函数的工作示例,该函数可在2个新窗口中打开文件。 However, I obviously get a blank window if the second location doesn't exist. 但是,如果第二个位置不存在,我显然会得到一个空白窗口。 I'd like the second page to not be opened if the reference does not exist. 如果引用不存在,我希望不打开第二页。

function OpenFile() {
    win=window.open('http://yadayada.org/~(student_number).pdf', '_self');
    win2=window.open('http:/yadayada.org/~(student_number)a.pdf', '_blank');
    win.focus();
}

OpenFile();

You will need to check the http status code of the URL using JavaScript to determine if the page exists, and if so then open the link. 您需要使用JavaScript检查URL的http状态代码,以确定该页面是否存在,然后打开该链接。

If you are using jQuery then it makes life easier: Use javascript to check http status codes 如果您使用的是jQuery,那么它将使生活更轻松: 使用javascript检查http状态代码

Otherwise you can use plain old JavaScript: How to get HTTP status from JavaScript 否则,您可以使用普通的旧JavaScript: 如何从JavaScript获取HTTP状态

[Edit] As mentioned in the comments, this will not work cross-domain. [编辑]如评论中所述,这不适用于跨域。

You could try the following - force the request to be JSONP by adding the ?callback=? 您可以尝试以下操作-通过添加?callback=? 强制将请求变为JSONP ?callback=? parameter to the request, but you need to look at the .fail callback since the pdf is obviously not JSON data. 参数,但您需要查看.fail回调,因为pdf显然不是JSON数据。 Also, be aware that the entire PDF is downloaded, so there will be a delay for large files. 另外,请注意,整个PDF均已下载,因此大文件会有所延迟。

var url = "http://samplepdf.com/sample.pdf?jsoncallback=?";
$.getJSON(url)
    .fail(function( jqxhr, textStatus, error ) {
        if (jqxhr.status == 200) {
            console.log("request document found success");
        }
    })

"Working" Demo: http://jsfiddle.net/WmHjs/ “工作中”的演示: http : //jsfiddle.net/WmHjs/

I would try and make the call server side if you require cross-domain checking. 如果您需要跨域检查,我会尝试在呼叫服务器端进行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM