[英]How to create a drop-down menu with html <select> in jquery and populate it with the response (a list) of the ajax call?
[英]Populate a drop-down in Vue.js from an ajax call
我希望能够进行ajax调用并使用返回的结果生成使用vue.js的下拉选项。 我可以做这个:
<select v-model="selected">
<option v-for="option in options" v-bind:value="option.value">
{{ option.text }}
</option>
</select>
<span>Selected: {{ selected }}</span>
.js文件
new Vue({
el: '...',
data: {
selected: 'A',
options: [
{ text: 'One', value: 'A' },
{ text: 'Two', value: 'B' },
{ text: 'Three', value: 'C' }
]
}
})
但我不想让我的选项硬编码,而是来自ajax调用。
Ajax调用看起来像这样:
function pullEmployees(){
var eventOwnerId = $('#eventOwner').val();
var eventOwnerName = $('#eventOwner :selected').text();
$.ajax({
url: "employees.cfm",
data: {
eventOwnerId: eventOwnerId,
eventOwnerName: eventOwnerName,
method : "updateOwners"
},
success: function(results) {
// results will have a list of objects where each objects has two properties (ID and Value)
}
});
}
我是vue.js的新手 ,如果有人可以提供帮助,我将不胜感激。
在下面的示例中,我使用setTimeout
模拟您的ajax调用。 基本上你想要在变量中捕获new Vue()
的结果,然后用你的ajax调用的结果设置该Vue的options
属性。
我还更新了您的模板,以反映您返回的选项具有{ID, text}
结构。
console.clear() let app = new Vue({ el: '#app', data: { selected: 'A', options: [] } }) function pullEmployees(){ let options = [ { text: 'One', ID: 'A' }, { text: 'Two', ID: 'B' }, { text: 'Three', ID: 'C' } ]; setTimeout(() => app.options = options, 1000) } pullEmployees()
<script src="https://unpkg.com/vue@2.2.6/dist/vue.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <div id="app"> <select v-model="selected"> <option v-for="option in options" v-bind:value="option.ID"> {{ option.text }} </option> </select> <span>Selected: {{ selected }}</span> </div>
但是所有这一切都可以在Vue内部完成。 它不需要在外面完成。
let app = new Vue({
el: '#app',
data: {
selected: 'A',
options: []
},
methods:{
pullEmployees(){
var eventOwnerId = $('#eventOwner').val();
var eventOwnerName = $('#eventOwner :selected').text();
$.ajax({
url: "employees.cfm",
data: {
eventOwnerId: eventOwnerId,
eventOwnerName: eventOwnerName,
method : "updateOwners"
},
success: results => this.options = results
});
}
},
mounted(){
this.pullEmployees()
}
})
如果eventOwner
也是Vue的一部分,那么你可以从Vue获取该值作为数据属性。
将您的vue实例存储为变量:
var vue = new Vue(// stuff...);
然后为阿贾克斯小心的范围this
:
function pullEmployees(){
var _this = this; // bind "this" to local var
var eventOwnerId = $('#eventOwner').val();
var eventOwnerName = $('#eventOwner :selected').text();
$.ajax({
url: "employees.cfm",
data: {
eventOwnerId: eventOwnerId,
eventOwnerName: eventOwnerName,
method : "updateOwners"
},
success: function(results) {
_this.vue.data.options = results; // set data
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.