简体   繁体   中英

how do I access this jQuery variable?

I have the following code in my project that helps me do some very funky AJAX uploading.

<script>
    $(function(){
        var uploader = new qq.FileUploader({
            action: "{% url ... %}",
            element: $('#file-uploader')[0],
            multiple: true,
            onComplete: function(id, fileName, responseJSON) {
                if(responseJSON.success) {
                    alert("success!");
                } else {
                    alert("upload failed!");
                }
            },
            onAllComplete: function(uploads) {
                // uploads is an array of maps
                // the maps look like this: {file: FileObject, response: JSONServerResponse}
                alert("All complete!");
            },
            params: {
                'csrf_token': '{{ csrf_token }}',
                'csrf_name': 'csrfmiddlewaretoken',
                'csrf_xname': 'X-CSRFToken',
                'iID': '{{ itemID }}',
                'received': $('letter_received').val(),
                'is_company': $('letter_is_company').val(),
            },
        });
    });
</script>

The only problem is I want to pass additional GET values to the server. I have tried the above but the script gets executed when the page opens, not when the values change. In the link above under ' Sending additional params ' the author recommends adding additional values at runtime by using the following code:

uploader.setParams({
   anotherParam: 'value'
});

I just don't know how I can access the uploader variable. Take the following for example:

<button onclick="update_uploader(1,0)">
...
<script>
    function update_uploader(received,is_company) {
        uploader.setParams({
            received: received,
            is_company: is_company
        });
    }
</script>

I can't access uploader because of scope issues. [and yes I have tried declaring uploader outside of $(function(){ but it breaks the uploader :(]

Any ideas?

Change var uploader to uploader . This will make your variable global.

The uploader in your code is a local variable, if you want to access this variable outside de function() you must declare updloader as global variable (but this is almost never recomend, but is indeed out of scope here). To solve your problem just change:

var uploader = new qq.FileUploader({
        action: "{% url ... %}",
        ....
});

to

window.uploader = new qq.FileUploader({
        action: "{% url ... %}",
        ....
});

Then the uploader will be available globally in the page.

您无需将此代码放在jQuery $(function(){块中。删除代码中的第一行和最后一行应该可以。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM