我有以下脚本。当我执行ajax函数时,它会使用更新后的值在控制台中正确打印photobombAvatar。但是,我无法将photobombAvatar更新为全局变量。
<script>
var photobombAvatar = "<?php echo $this->user_data['avatar']; ?>";
$(function () {
var uploader = new ss.SimpleUpload({
button: btn,
url: '<?php echo $this->form_action; ?>',
sessionProgressUrl: 'data/js/plugins/thisSCRIPT.php',
name: 'file',
debug: true,
data: {name: 'upload_avatar'},
responseType: 'json',
onSubmit: function (filename, ext) {
// do a bunch of stuff
},
onComplete: function(file, json) {
if (json.success) {
var pic = new Pic();
var photobombAvatar = json.success;
pic.src = json.success;
}
console.log(photobombAvatar);
}
});
});
//another js fxn that uses the updated global photobombAvatar.
</script>
我已经阅读了许多使用回调函数的示例,但似乎无法使其正常工作。这是我尝试过的一个示例:
<script>
var photobombAvatar = "<?php echo $this->user_data['avatar']; ?>";
$(function photobomb(callback) {
var uploader = new ss.SimpleUpload({
button: btn,
url: '<?php echo $this->form_action; ?>',
sessionProgressUrl: 'data/js/plugins/thisSCRIPT.php',
name: 'file',
debug: true,
data: {name: 'upload_avatar'},
responseType: 'json',
onSubmit: function (filename, ext) {
// do a bunch of stuff
},
onComplete: function(file, json) {
if (json.success) {
var pic = new Pic();
var photobombAvatar = json.success;
pic.src = json.success;
callback(json);
}
console.log(photobombAvatar);
updatedVAR(photobombAvatar);
}
});
});
photobomb();
function updatedVAR(photobombAvatar) {
console.log(photobombAvatar);
// do the rest of the js I need with the updated photobombAvatar value.
}
</script>
预先感谢您的任何建议或想法。
答案 0 :(得分:0)
您正在onComplete函数中定义新的photobombAvatar
。在photobombAvatar之前删除var
。喜欢:
onComplete: function(file, json) {
if (json.success) {
var pic = new Pic();
var photobombAvatar = json.success;
pic.src = json.success;
callback(json);
}
更改为:
onComplete: function(file, json) {
if (json.success) {
var pic = new Pic();
photobombAvatar = json.success;
pic.src = json.success;
callback(json);
}