简体   繁体   中英

Assigning a dynamic variable in Javascript in a template for URLs

I am working on trying to assign a dynamic variable in Javascript within my template for URLs. This is to pass the data back to the page. At the moment this is hard coded. I'm stuck trying to figure out best way to fix this. Here is my code:

JS

function MyModule.init() {
var myXHR = new XMLHttpRequest(),
    seconds = (new Date()).getTime();

// Load my data
myXHR.addEventListener('readystatechange', function () {
    var preXHR = new XMLHttpRequest(),
        data;

    if (myXHR.readyState === 4) {
        data = JSON.parse(myXHR.responseText);

        timestamp = data['timestamp'];
        myData = data['my'];

        // Load rep data
        preXHR.addEventListener('readystatechange', function () {
            if (preXHR.readyState === 4) {
                repData = JSON.parse(preXHR.responseText)['reps'];

                organizeData();
                showMYTable();
            }
        });

        // This hardcoded path is what I am trying to change, as it is bad
        preXHR.open('GET', '/catalog/1/my-reps?t=' + seconds); 

        preXHR.send();
    }
});

// This hardcoded path is what I am trying to change, as it is bad
myXHR.open('GET', '/catalog/1/my-data?t=' + seconds);

myXHR.send();

TEMPLATE

<script>
    $(function(){
        MyModule.init('{% url catalog.data %}');
    });
</script>

URL

url(r'^(?P<company>.+)/(?P<name>.+)', 'data', name='catalog.data')

You seem to be already passing the URL into the MyModule.init() function, but you're not doing anything with it there. Just reference it as a variable:

function MyModule.init(url) {
    ...

    myXHR.open('GET', url + '?t=' + seconds);

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