I'm using the the jQuery fileupload plugin and configure it like this:

jQuery(document).ready(function() {
  jQuery("#fileupload").fileupload({
    dataType: "json",
    url: "ajax_handler.php?globalVar=" + globalVar,
    send: function (e, data) {

    },
    done: function (e, data) {

    }
});

....

Where globalVar is (wait for it) a global variable.

The problem is that if I change the value of globalVar and then do a file upload (using the jQuery file upload plugin which is AJAX so that the page doesn't change), the URL that the request is made to has the original globalVar value (that it had when the page first loaded).

Why is this happening?

有帮助吗?

解决方案

When you create the file upload widget, you're passing it a configuration object. This object has a number of properties, among them url.

The property values are evaluated when the object is created (in your case when you create the file upload widget in $(document).ready()). The object has no knowledge of the globalVar variable since the value that is assigned:

"ajax_handler.php?globalVar=" + globalVar

evaluates to a simple string (you're not passing it a reference to globalVar or anything like that). The behavior you seem to be expecting could only happen if you'd assign a function to the url property in which you reference globalVar (I don't know whether the file upload plugin supports this).

So even if you change globalVar at a later time, the file upload widget's url configuration option will stay the same. If you want to change it, you need to explicitly assign it again.

其他提示

If you want a variable value to persist from one page to another, then you have to store that value somewhere and then retrieve it from the other page. Javascript variables are local to a page so the entire javascript state is cleared each time you go to a new page. The options for storing/retrieving the variable are:

  1. Store it and retrieve if from a cookie
  2. Store it and retrieve it from LocalStorage
  3. Store it and retrieve it on your server (probably using AJAX)

The first two are simpler if you don't need it stored on the server. The advantage of the server is that it can be available even from other computers. The cookie and LocalStorage are only available on that particular computer.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top