我根据本教程创建了一个简单的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';?>
2 回答
POPMUISE
TA贡献1765条经验 获得超5个赞
您可以使用filter_var
带有FILTER_VALIDATE_URL
标志的方法,如下所示:
var_dump(filter_var($_POST['dlink'], FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED));
可选FILTER_FLAG_SCHEME_REQUIRED
标志用于通过http / https验证输入
关于您的代码的另一条注释:name
url输入字段中有2个属性。
因此,您可以$dlink
使用以下filter_input
方法设置var :
$dlink = filter_input(INPUT_POST, 'dlink', FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED);
- 2 回答
- 0 关注
- 137 浏览
添加回答
举报
0/150
提交
取消