Answer the question
In order to leave comments, you need to log in
Is it correct to use ajax request in the model?
Hello! I would like to get a code review of this model!
The project uses mvc and in the model there is an increase / decrease in the value in the methods and sending an ajax request with this value, and then writing the received response from the server back to the model constructor, and then manipulate them in the future!
class TestModel {
constructor() {
super();
this._result = {
count: 1,
product: 0,
allPrice: 0
};
}
getItems() {
return this._result;
}
addItem(result) {
const params = {
evt: 'countAdd',
result: result
}
// увеличиваем count на 1
this._result.count = result.count + 1;
// и передаём его в ajax запрос
this.getAjax(this._result.count, params);
}
remItem(result) {
const params = {
evt: 'countRemove',
result: result
}
this._result.count = result.count - 1;
this.getAjax(this._result.count, params);
}
getAjax(count, params) {
const _this = this;
$.ajax({
url: 'send-test.php',
type: "POST",
dataType: "html",
data: {'count': count},
success: function (response) {
// получаем ответ и результат записываем в конструктор модели
// от куда потом через метод getItems получаем данные для вывода во View
var result = $.parseJSON(response);
_this._result.all = result.allPrice;
setTimeout(() => {
_this.emit(params.evt, params.result);
}, 100);
},
error: function (response) {
console.log('fail!');
}
});
}
}
export default TestModel;
Answer the question
In order to leave comments, you need to log in
Logically, it looks correct. The model is responsible for working with data
Since you have mvc in js, I can suggest using axios instead of jquery
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question