主要思想是仅使用vue.js进行“实时”字段验证。但是该表单仅由PHP通过POST方法发送。 vue.js接管所有形式并阻止php在此过程中继续进行的问题。
我的代码:
<?php
if(!empty($_POST['name'])){
//do something
}
?>
<form method="POST">
<div id="app">
<b-container>
<b-form-group horizontal :label-cols="4" description="Let us know your name." label="Enter your name">
<b-form-input id="input-live" v-model="name" :state="nameState"
aria-describedby="input-live-help input-live-feedback" placeholder="Enter your name" trim>
</b-form-input>
<b-form-invalid-feedback id="input-live-feedback">
Enter at least 3 letters (english only)
</b-form-invalid-feedback>
</b-form-group>
</b-container>
</div>
<input type="submit">
</form>
<script type="text/javascript">
function get_data_from_url(url) {
var http_req = new XMLHttpRequest();
http_req.open("GET", url, false);
http_req.send(null);
return http_req.responseText;
}
window.app = new Vue({
el: '#app',
data: {
name: ''
},
computed: {
nameState() {
var url = "core/valid.php?name=" + encodeURIComponent(this.name);
var data_obj = JSON.parse(get_data_from_url(url));
return (data_obj['status'] == "success") ? true : false;
}
},
data() {
return {
name: ''
}
}
});
</script>
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css" />
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.css" />
<!-- Required scripts -->
<script src="//unpkg.com/vue@latest/dist/vue.js"></script>
<script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.js"></script>
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.4.1.min.js"></script>
这应该可以按预期工作。我用您的代码创建了一个jsfiddle,但更改了两件事: