我正在尝试将我的Jquery代码转换为函数以使其更具动态性。作为参数,我想传递Handlebars SCRIPT标签的ID,打印结果的DIV标签的ID,AJAX的查询URL和Ajax的参数。
我只使用参数(URL和参数)进行了一些测试,但我没有得到任何结果(显然这是异步方法的问题,但对我来说不是很清楚)。
这是原始功能代码:
var source = document.getElementById("entry-template").innerHTML;
var template = Handlebars.compile(source);
var context = $.post("http://localhost/api/api.php", {a: 'foo', b: 'bar'});
context
.then((response) => {
var parsejson = JSON.parse(response);
$("#content-placeholder").html(template({objects:parsejson}));
});
这是我提出的简化以前代码的功能:
function testing (id, target, url, parameters){
var source = document.getElementById(id).innerHTML;
var template = Handlebars.compile(source);
var context = $.post(url, parameters);
context
.then((response) => {
var parsejson = JSON.parse(response);
return $(target).html(template({objects:parsejson}));
});
};
var cool = testing("test-template", "#test-placeholder", "http://localhost/api/api.php", {a: 'foo', b: 'bar'});
console.log(cool);
但是我在控制台上得到了“未定义”。
答案 0 :(得分:1)
您正在学习承诺以及如何使用其承诺来处理异步操作,并且您的方法正确。
function testing (id, target, url, parameters){
var source = document.getElementById(id).innerHTML;
var template = Handlebars.compile(source);
var context = $.post(url, parameters);
return context
.then((response) => {
var parsejson = JSON.parse(response);
return $(target).html(template({objects:parsejson}));
});
};
testing("test-template",
"#test-placeholder",
"http://localhost/api/api.php",
{a: 'foo', b: 'bar'}
).then(function(cool){
console.log(cool);
});
这样,测试函数将返回promise
,您可以等到promise
完成,之后您就可以获得该值。
这是一个描述您的问题并为您提供解决方案的页面:
http://michaelsoriano.com/working-with-jquerys-ajax-promises-and-deferred-objects/