猿问

如何使用AJAX表单验证URL字段

我根据本教程创建了一个简单的ajax表单,并且一切正常。我唯一的问题是我无法弄清楚如何验证URL字段的数据。似乎即使我将字段类型设置为URL,但如果不是URL,它仍然会处理。


有任何想法吗?


example.html


<html>

<head>

<script>

function ajax_post(){

    // Create our XMLHttpRequest object

    var hr = new XMLHttpRequest();

    // Create some variables we need to send to our PHP file

    var url = "my_parse_file.php";

    var dlink = document.getElementById("dirtylink").value;

   var vars = "dlink="+dlink;

    hr.open("POST", url, true);

    // Set content type header information for sending url encoded variables in the request

    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    // Access the onreadystatechange event for the XMLHttpRequest object

    hr.onreadystatechange = function() {

      if(hr.readyState == 4 && hr.status == 200) {

        var return_data = hr.responseText;

      document.getElementById("status").innerHTML = return_data;

      }

    }

    // Send the data to PHP now... and wait for response to update the status div

    hr.send(vars); // Actually execute the request

    document.getElementById("status").innerHTML = "processing...";

}

</script>

</head>

<body>

<h2>Ajax Post to PHP and Get Return Data</h2>

<input id="dlink" name="dlink" class="putfield" type="url" pattern="https?://.+" required name="website">

<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();"> <br><br>

<div id="status"></div>

</body>

</html>

my_parse_file.php


<?php 

echo 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says 

the PHP file';

?>


侃侃尔雅
浏览 138回答 2
2回答

POPMUISE

您可以使用filter_var带有FILTER_VALIDATE_URL标志的方法,如下所示:var_dump(filter_var($_POST['dlink'],&nbsp;FILTER_VALIDATE_URL,&nbsp;FILTER_FLAG_SCHEME_REQUIRED));可选FILTER_FLAG_SCHEME_REQUIRED标志用于通过http / https验证输入关于您的代码的另一条注释:nameurl输入字段中有2个属性。因此,您可以$dlink使用以下filter_input方法设置var&nbsp;:$dlink&nbsp;=&nbsp;filter_input(INPUT_POST,&nbsp;'dlink',&nbsp;FILTER_VALIDATE_URL,&nbsp;FILTER_FLAG_SCHEME_REQUIRED);
随时随地看视频慕课网APP
我要回答