<script>
var addUser = function() {
var defer = $.Deferred()
$.ajax("http://localhost/PhpProject1/index.php", {
type: "POST",
jsonpCallback: 'yes',
data: {username: 'test'},
contentType: "application/json",
dataType: "jsonp"
});
success:(function(data) {
defer.resolve(data);
})
}
filtered = defer.then(function(value) {
return value;
});
filtered.done(function(value) {
console.log(value);
});
$("button").on("click", addUser);
</script>
我创建了上面的函数来从jsnop中检索数据。我使用了Deffered。但是当我尝试这段代码时,我得到了以下错误。
Uncaught ReferenceError: defer is not defined
答案 0 :(得分:0)
如果您从defer.promise
返回addUser
,则可以设置如下
var addUser = function () {
var defer = $.Deferred()
/* ajax and resolve/reject*/
return defer
}
var filtered = addUser().then(function (value) {
return value;
});
$.ajax()
也会返回一个承诺。如果不直接创建新的$.Deferred
var addUser = function () {
return $.ajax({ /* ajax options*/})
}