【发布时间】:2017-03-05 16:49:27
【问题描述】:
我有这个 vue 函数,基本上有两种方法。第一个postStatus 用于在用户单击保存按钮后保存帖子,另一个getPosts 用于从数据库中检索该用户以前的所有帖子。
这里是 vue.js,其中有一个对控制器的 ajax 调用(在 Laravel 5.3 中)
$(document).ready(function () {
var csrf_token = $('meta[name="csrf-token"]').attr('content');
/*Event handling within vue*/
//when we actually submit the form, we want to catch the action
new Vue({
el : '#timeline',
data : {
post : '',
posts : [],
token : csrf_token,
limit : 20,
},
methods : {
postStatus : function (e) {
e.preventDefault();
//console.log('Posted: '+this.post+ '. Token: '+this.token);
var request = $.ajax({
url : '/posts',
method : "POST",
dataType : 'json',
data : {
'body' : this.post,
'_token': this.token,
}
}).done(function (data) {
//console.log('Data saved successfully. Response: '+data);
this.post = '';
this.posts.unshift(data); //Push it to the top of the array and pass the data that we get back
}.bind(this));/*http://stackoverflow.com/a/26479602/1883256 and http://stackoverflow.com/a/39945594/1883256 */
/*request.done(function( msg ) {
console.log('The tweet has been saved: '+msg+'. Outside ...');
//$( "#log" ).html( msg );
});*/
request.fail(function( jqXHR, textStatus ) {
console.log( "Request failed: " + textStatus );
});
},
getPosts : function () {
//Ajax request to retrieve all posts
$.ajax({
url : '/posts',
method : "GET",
dataType : 'json',
data : {
limit : this.limit,
}
}).done(function (data) {
this.posts = data.posts;
}.bind(this));
}
},
//the following will be run when everything is booted up
ready : function () {
console.log('Attempting to get the previous posts ...');
this.getPosts();
}
});
});
到目前为止,第一种方法postStatus 运行良好。
第二个应该在 ready 函数中被调用或触发,但是什么也没发生。我什至没有收到 console.log 消息Attempting to get the previous posts ...。它似乎从未被解雇过。
有什么问题?我该如何解决?
注意:我使用的是 jQuery 3.1.1,Vue.js 2.0.1
【问题讨论】:
标签: javascript jquery ajax vue.js