我正在尝试使用 jQuery 和 Vue.js 实现一些东西:
这是我的脚本部分:
<script>
function initVM(result) {
// alert(result.num)
var vm2 = new Vue({
el: '#vm2',
data: {
// ③bind one item of the result as example
rrr: result.num
}
});
$('#vm2').show();
}
$(function() {
var vm = new Vue({
el: '#vm',
data: {
content: ''
},
methods: {
submit: function(event) {
event.preventDefault();
var
$form = $('#vm'),
content = this.content.trim();
// ①post textarea content to backend
$form.postJSON('/api/parse', {
content: content
}, function(err, result) {
if (err) {
$form.showFormError(err);
}
else {
// ②receive a result dictionary
$('#vm').hide();
initVM(result);
}
});
}
}
});
});
</script>
这是我的 html 部分:
<html>
<form id="vm", v-on="submit: submit">
<textarea v-model="content" name="content"></textarea>
<button type="submit">Have a try!</button>
</form>
<div id="vm2" style="diplay:none;">
<!-- ④show the result-->
The result:
{{ rrr }}
</div>
</html>
这是 postJSON
的定义
<script>
// ...
postJSON: function (url, data, callback) {
if (arguments.length===2) {
callback = data;
data = {};
}
return this.each(function () {
var $form = $(this);
$form.showFormError();
$form.showFormLoading(true);
_httpJSON('POST', url, data, function (err, r) {
if (err) {
$form.showFormError(err);
$form.showFormLoading(false);
}
callback && callback(err, r);
});
});
// ...
// _httpJSON
function _httpJSON(method, url, data, callback) {
var opt = {
type: method,
dataType: 'json'
};
if (method==='GET') {
opt.url = url + '?' + data;
}
if (method==='POST') {
opt.url = url;
opt.data = JSON.stringify(data || {});
opt.contentType = 'application/json';
}
$.ajax(opt).done(function (r) {
if (r && r.error) {
return callback(r);
}
return callback(null, r);
}).fail(function (jqXHR, textStatus) {
return callback({'error': 'http_bad_response', 'data': '' + jqXHR.status, 'message': 'something wrong! (HTTP ' + jqXHR.status + ')'});
});
}
</script>
该过程可以描述为:
- 将内容发布到后端
- 接收结果并隐藏表单
- 使用结果创建一个新的 Vue
- 在与新 Vue 实例绑定(bind)的 div 中显示结果
事实上,我确实成功收到了结果,alert(result.num)
证明了这一点。声明,但在 vm2
中找不到任何内容的 div 除了 The result:
问题出在哪里?或者,如果有的话,请随意教我一种更简单的方法,因为我认为我使用的不是一个好的方法。
最佳答案
提问者来了。
终于找到问题出在哪里了。
问题出在 mustache 上:{{ }}
我使用jinja2(Python 模板引擎)和Vue.js(MVVM 前端框架)。它们都使用 {{ }}
作为分隔符。
因此,如果有人陷入与我相同的情况(我认为不会出现这种情况),请:
app.jinja_env.variable_start_string = '{{ '
app.jinja_env.variable_end_string = ' }}' # change jinjia2 config
或者
Vue.config.delimiters = ['${', '}'] # change vue config
关于javascript - 处理postJSON的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37932996/