How can I retrieve json in Vuejs in vue.js in laravel 4?
I tried following but it didn't work:
new Vue({
el: '#guestbook',
data: {
comments: [],
text: '',
author: ''
},
ready: function() {
this.getMessages();
},
methods: {
getMessages: function() {
$.ajax({
context: this,
url: "/cms/Getweb_manager",
success: function (result) {
this.$set("comments", result)
}
})
}
}
})
Have you tried logging the response? Just use a console.log(result).
About your doubt, you probably have to do this.$set('comments', result.data');.
Don't forget the semicolon!
Have a look at the vue-resource package
https://github.com/vuejs/vue-resource
It should work like this
methods: {
getMessages: function() {
this.$http({
url: '/cms/Getweb_manager',
method: 'GET'
}).then(function (response) {
// success callback
this.$set('comments', response.result);
}, function (response) {
// error callback
});
}
}
Related
I am building a web application with django-rest-framework and extjs5.
Obviously i faced problems with django's csrf token, which i had to inlude in Extjs's Ajax requests.
But while i implemented POST method successfully, it seems that my implementation doesn't work for PUT and DELETE method.
My POST method code:
onSaveRecordBtnClick: function(){
Job_Name = this.lookupReference('Job_Name').getValue();
var csrf = Ext.util.Cookies.get('csrftoken');
Ext.Ajax.request({
url: '/jobs_api/job/',
method: "POST",
params: {
Job_Name: Job_Name,
'csrfmiddlewaretoken': csrf
},
success: function(conn, response, options, eOpts) {
var result = MyApp.util.Util.decodeJSON(conn.responseText);
if (result.success) {
alert('Job Submission Successfull');
}
else {
MyApp.util.Util.showErrorMsg(conn.responseText);
}
},
failure: function(conn, response, options, eOpts) {
MyApp.util.Util.showErrorMsg(conn.responseText);
}
});
}
This works perfectly, but when i try PUT or DELETE method i keep getting:
Request Method:DELETE
Status Code:403 FORBIDDEN
{"detail":"CSRF Failed: CSRF token missing or incorrect."}
My DELETE method:
onJobDblClick : function(grid, record, index, eOpts) {
var job_id = record.id;
var csrf = Ext.util.Cookies.get('csrftoken');
Ext.Ajax.request({
url: '/jobs_api/job/' + job_id + '/',
method: "DELETE",
params: {
'id': job_id,
'csrfmiddlewaretoken': csrf
},
success: function(conn, response, options, eOpts) {
var result = MyApp.util.Util.decodeJSON(conn.responseText);
if (result.success) {
alert('Job Deleted Successfully');
}
else {
MyApp.util.Util.showErrorMsg(conn.responseText);
}
},
failure: function(conn, response, options, eOpts) {
MyApp.util.Util.showErrorMsg(conn.responseText);
}
});
}
My job model is:
Ext.define('MyApp.model.Job', {
extend: 'MyApp.model.Base',
fields: [
{ name: 'id', type: 'int' },
{ name: 'Job_Name', type: 'string' },
],
proxy: {
type: 'rest',
url: '/jobs_api/job/',
reader: {
type: 'json',
rootProperty: 'data'
}
}
});
I don't know why this is happening. Please help!!
I'm new to Ember js and I'm having some difficulty seeing why this isn't working. Essentially i'm sending a GET request to a server and it is giving me an array. I would like to take that array display its contents.
app.js
App.TestRoute = Ember.Route.extend({
model: function(){
return App.Test.findAll();
}
});
App.Test = Ember.Object.extend();
App.Test.reopenClass({
findAll: function() {
var dummyArray = [];
$.ajax({
type: 'GET',
url: 'myurl',
headers: {'myheader'},
success: function(data){
data.dummyArray.forEach(function (item){
dummyArray.push(App.Test.create(item));
});
return dummyArray;
},
error: function(request, textStatus, errorThrown){
alert(errorThrown);
console.log();
}
});
}
});
When you to the test page the action should fire and an array should be returned to the model where the data can be grabbed to populate the page
and in my HTML I have this:
script type="text/x-handlebars" id="test">
<ul>
{{#each item in model}}
<li>{{item.ID}}</li>
{{/each}}
</ul>
{{outlet}}
</script>
In the console when I log the data that I returned it looks something like this:
Object {dummyArray: Array[4]}
dummyArray: Array[4]
0: Object
ID: 1111
1: Object
ID: 1112
2: Object
ID: 1113
3: Object
ID: 1114
The app runs with no errors but when I navigate to my test page the page does not populate with any data.
Your problem is that your synchronous code is returning nothing. Your model function returns App.Test.findAll(), which is never anything. You need to return a promise.
findAll: function () {
var result = [];
return new Ember.RSVP.Promise(function (resolve, reject) {
Ember.$.ajax({
type: 'GET',
url: 'myurl',
headers: { 'myheader' },
success: function (data) {
data.dummyArray.forEach(function (item) {
result.push(App.Test.create(item));
});
resolve(result);
},
error: function (request, textStatus, error) {
console.log(error);
reject(error);
}
});
});
}
I am trying to pass knockout object as below,
When i pass the data using // ko.utils.postJson only without any the AJAx the data is passed to my controller to the "task", but when i try to post by Ajax I get a null value for task
function TaskListViewModel() {
var self = this;
self.availableMeals = [
{ UserName: "Standard", UserId: 0 },
{ UserName: "Premium", UserId: 34 },
{ UserName: "Ultimate", UserId: 290 }
];
self.save = function () {
// ko.utils.postJson(location.href, { task: this.availableMeals });
$.ajax(location.href,{
data: ko.toJSON({ task: this.availableMeals });,
type: 'POST',
dataType:'json',
contentType: 'application/json',
success: function (result) { alert(result) }
});
};
}
ko.applyBindings(new TaskListViewModel());
To the Controller as below,
[HttpPost]
public ActionResult About([FromJson] IEnumerable<UserProfile> task)
{
return RedirectToAction("Login","Account");
}
I would try changing your code to call the stored self reference in your Ajax call as follows:
$.ajax(location.href,{
data: ko.toJSON({ task: self.availableMeals });,
type: 'POST',
dataType:'json',
contentType: 'application/json',
success: function (result) { alert(result) }
});
};
I'm guessing that you are having a scope issues where this is losing it's reference in your Ajax call.
If I have the following factories:
.factory('User', function($resource) {
return $resource('/users/:id', {id: "#id"}, {
query: {method: 'GET', params: {}, isArray: false}
});
})
.factory('UserList', function(User, $q) {
var deferred = $q.defer();
User.query({}, function(response) {
deferred.resolve(response.data);
});
return deferred.promise;
})
I know have a UserList that I can inject into all my controllers that need it. But, if I later in my application create a new user, how can I make the 'UserList'-factory "refresh"? Is there another approach that is (even) more "The Angular Way"?
I'm making an ajax request to retrieve json data from webtrends - a service that requires a login. I'm passing the username and password in my ajax request, but still gives me a 401 unauthorized error. I've tried 3 different methods - but no luck. Can someone pls help me find a solution?
1. $.getJSON('https://ws.webtrends.com/..?jsoncallback=?', { format: 'jsonp', suppress_error_codes: 'true', username: 'xxx', password: 'xxx', cache: 'false' }, function(json) {
console.log(json);
alert(json);
});
2. $.ajax({
url: "https://ws.webtrends.com/../?callback=?",
type: 'GET',
cache: false,
dataType: 'jsonp',
processData: false,
data: 'get=login',
username: "xxx",
password: "xxx",
beforeSend: function (req) {
req.setRequestHeader('Authorization', "xxx:xxx");
},
success: function (response) {
alert("success");
},
error: function(error) {
alert("error");
}
});
3. window.onload=function() {
var url = "https://ws.webtrends.com/...?username=xxx&password=xxx&callback=?";
var script = document.createElement('script');
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);
}
function parseRequest(response) {
try {
alert(response);
}
catch(an_exception) {
alert('error');
}
}
Method 3 might work when you use a named callback function and use basic authentication in the url. Mind though that a lot of browsers don't accept url-authentication (or whatever the name is). If you want to try it, you can rewrite it like this:
window.onload = function() {
var url = "https://xxx:xxx#ws.webtrends.com/...?callback=parseRequest";
var script = document.createElement('script');
script.setAttribute('src', url);
document.getElementsByTagName('head')[0].appendChild(script);
}
function parseRequest(response) {
try {
alert(response);
}
catch(an_exception) {
alert('error');
}
}