简体   繁体   中英

Pass a variable to Ajax URL

I'm trying to add a variable (integer) in URL to be used in an Ajax request:

In my HTML, I have:

<span class="user">15</span>

And the script:

$('#fileupload').click(function () {
    $(this).fileupload({
        dataType: 'json',
        done: function (e, data) {
            $.each(data.result.files, function (index, file) {
                if (file.error != null) {
                    $console.text(file.error);
                }
                var user = parseInt($(".user").text(), 10);
                //Open the uploaded file//
                $.ajax({
                    url: "files/" + user + '/' + file.name,
                    dataType: 'json',
                    type: 'GET',
                    success: function (res) {
                        handsontable.loadData(res.data);
                        $console.text('Loaded file: ' + file.name);
                    }
                });
            });
        }
    });
});

However, the variable (15) isn't being passed to the URL, I get the error:

/files/NaN/data.json

I know I'm doing something stupid, and searched everywhere, but what is it?

You don't really have to parse int it, because you're just putting it back into a string. Try removing the parse int then consol logging the value of the user variable.

Also, perhaps you have many user elements? Console log $(".user") to see if you get an array.

It looks like the parsing fails and you get NaN (not-a-number) instead.

Can you verify that the input string to parseInt looks like a number?

Also, you're converting user back into a string. Do you really need to parseInt here?

I suggest you try to run $('.user').text() in chrome console (F12) (for example) to see if you have some empty value or thing like that.

I believe that this approach can help you.

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