通过 PHP&AJAX 自动链接短路 (bit.ly) [英] Auto Link shorting via PHP&AJAX (bit.ly)

查看:21
本文介绍了通过 PHP&AJAX 自动链接短路 (bit.ly)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想构建一个只有一个字段(url - 链接缩短)的表单(通过 POST 方法).现在的问题是如何以及是否可以构建一个表单来检测 URL 字段的值是一个链接并自动缩短它,而不是等待您点击发送(例如像 Bit.ly 的网站).

I would like to build a form (VIA POST METHOD) with just one field (url - link shortening). Now the question is how and if is it possible to build a form that detects the value of the URL field is a link and automatically shortens it rather than waiting you click Send (for exmaple like the web of Bit.ly).

主要思想是一旦该字段是一个标识符,该值是一个适当的超链接,直接发送并缩短(并且该字段被缩短的链接替换)它,而无需等待点击发送.

The main idea is once the field is an identifier that value is a proper Hyperlink is directly sends and shortens (And the field is replaced by a shortened link) it without waiting for the click on the SEND.

index.html

<html>
<head>
<script>
function showHint(str) {
    if (str.length == 0) { 
        document.getElementById("txtHint").innerHTML = "";
        return;
    } else {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("txtHint").innerHTML = this.responseText;
            }
        };
        xmlhttp.open("GET", "gethint.php?q=" + str, true);
        xmlhttp.send();
    }
}
</script>
</head>
<body>

<p><b>Start typing a url in the input field below:</b></p>
<form> 
Url: <input type="text" onkeyup="showHint(this.value)">
</form>
<p><span id="txtHint"></span></p>
</body>
</html>

gethint.php

gethint.php

 <?php  
// get the q parameter from URL 

    $q = $_REQUEST["q"];

        $hint = "";

    if (!filter_var($q, FILTER_VALIDATE_URL) === FALSE) {    

    // short the link 

    $rand = rand(1,1000); 

    $hint = 'http://domain.com/'.$rand;    }

    echo $hint === "" ? "Not a valid URL" : $hint; ?>

推荐答案

我会使用 jQuery 来触发事件/AJAX 和 https://gist.github.com/dperini/729294 用于 weburl 正则表达式.

I'd use jQuery for the event triggering/AJAX and https://gist.github.com/dperini/729294 for weburl regex.

我对纯 JavaScript AJAX 调用不太熟悉,但是

I'm not that at home on pure JavaScript AJAX calls, but is

xmlhttp.open("GET")

如果您想发布帖子,正确的方法是什么?

the right way to go at it if you want to make a POST?

无论如何,您缺少的主要内容是

Anyway the main thing you're missing is

function isUrl(url){
        var regex = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i;
        if(regex.test(url)){
             return regex.test(url);
        }else{
             return regex.test("http://"+url);
        }
}

所以这应该是你的新 index.html

So this should be your new index.html

<html>
<head>
<script>
var extensions = [".aero",".biz",".cat",".com",".coop",".edu",".gov",".info",".int",".jobs",".mil",".mobi",".museum",".name",".net",".org",".travel",".ac",".ad",".ae",".af",".ag",".ai",".al",".am",".an",".ao",".aq",".ar",".as",".at",".au",".aw",".az",".ba",".bb",".bd",".be",".bf",".bg",".bh",".bi",".bj",".bm",".bn",".bo",".br",".bs",".bt",".bv",".bw",".by",".bz",".ca",".cc",".cd",".cf",".cg",".ch",".ci",".ck",".cl",".cm",".cn",".co",".cr",".cs",".cu",".cv",".cx",".cy",".cz",".de",".dj",".dk",".dm",".do",".dz",".ec",".ee",".eg",".eh",".er",".es",".et",".eu",".fi",".fj",".fk",".fm",".fo",".fr",".ga",".gb",".gd",".ge",".gf",".gg",".gh",".gi",".gl",".gm",".gn",".gp",".gq",".gr",".gs",".gt",".gu",".gw",".gy",".hk",".hm",".hn",".hr",".ht",".hu",".id",".ie",".il",".im",".in",".io",".iq",".ir",".is",".it",".je",".jm",".jo",".jp",".ke",".kg",".kh",".ki",".km",".kn",".kp",".kr",".kw",".ky",".kz",".la",".lb",".lc",".li",".lk",".lr",".ls",".lt",".lu",".lv",".ly",".ma",".mc",".md",".mg",".mh",".mk",".ml",".mm",".mn",".mo",".mp",".mq",".mr",".ms",".mt",".mu",".mv",".mw",".mx",".my",".mz",".na",".nc",".ne",".nf",".ng",".ni",".nl",".no",".np",".nr",".nu",".nz",".om",".pa",".pe",".pf",".pg",".ph",".pk",".pl",".pm",".pn",".pr",".ps",".pt",".pw",".py",".qa",".re",".ro",".ru",".rw",".sa",".sb",".sc",".sd",".se",".sg",".sh",".si",".sj",".sk",".sl",".sm",".sn",".so",".sr",".st",".su",".sv",".sy",".sz",".tc",".td",".tf",".tg",".th",".tj",".tk",".tm",".tn",".to",".tp",".tr",".tt",".tv",".tw",".tz",".ua",".ug",".uk",".um",".us",".uy",".uz", ".va",".vc",".ve",".vg",".vi",".vn",".vu",".wf",".ws",".ye",".yt",".yu",".za",".zm",".zr",".zw"];

var delay = (function(){
    var timer = 0;
    return function(callback, ms){
       clearTimeout (timer);
       timer = setTimeout(callback, ms);
    };
 })();

function isUrl(url){
        var regex = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?$/i;
        if(regex.test(url)){
             return regex.test(url);
        }else{
             return regex.test("http://"+url);
        }
}
function showHint(str) {
 delay(function(){
      str = str.toLowerCase();
      var dot = str.lastIndexOf(".");
      var extension = str.substr(dot);
      extension = extension.split('/')[0];
      var found = $.inArray(extension, extensions) > -1;
         if (!isUrl(str)||!found) { 
             document.getElementById("txtHint").innerHTML = "";
             return;
         } else {
             var xmlhttp = new XMLHttpRequest();
             xmlhttp.onreadystatechange = function() {
                 if (this.readyState == 4 && this.status == 200) {
                     document.getElementById("txtHint").innerHTML = this.responseText;
                 }
             };
             xmlhttp.open("GET", "gethint.php?q=" + str, true);
             xmlhttp.send();
         }
     }, 500)
 }
</script>
</head>
<body>

<p><b>Start typing a url in the input field below:</b></p>
<form> 
Url: <input type="text" onkeyup="showHint(this.value)">
</form>
<p><span id="txtHint"></span></p>
</body>
</html>

假设您将开始输入 http://www.example.net .. AJAX将在http://www.example.ne"时触发,然后在您添加最后一个字母时再次触发.为避免这种情况,您可以尝试更改"而不是keyup"事件.

edit: Say you will start typing in http://www.example.net.. The AJAX will trigger on "http://www.example.ne" and then again when you add the last letter. To avoid that, you might try "change" instead of "keyup" event.

edit2:现在检查有效域扩展列表

edit2: Now checks against list of valid domain extensions

edit3:现在在发布结果之前等待半秒.

edit3: Now waits half a second before posting the result.

edit4:检查扩展时的小疏忽,修复了extension = extension.split('/')[0];

edit4: Small oversight while checking for extensions, fixed with extension = extension.split('/')[0];

此外,如果您想让用户编写没有http://"和类似内容的 URL,您需要编辑一个正则表达式或编写一个小技巧,在将其发送到isUrl()"之前将其添加到您的字符串中".

Also if you want to enable users to write URL's without "http://" and similar, you'll need an edited regex or write a small hack that adds that to your string before you send it into "isUrl()".

这篇关于通过 PHP&amp;AJAX 自动链接短路 (bit.ly)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆