简体   繁体   中英

How to pass JavaScript variable to jQuery ajax request

I am trying to pass a variable to an jquery ajax request:

$(document).ready(function() {
            // get page number
            var page = parseInt(getUrlParameter('page'));
            if (page < 1) page = 1;
            var page_next = page + 1;

          $.ajax({
                type: "GET",
                data: { 
                    page: page,

                },  
                dataType: 'json', 
           ...

unfortunatelly the variable "page" seems not to be present inside the ajax request. Doing an cosole.log(page); inside reveils "NaN" as a value.

The problem seems to be

if (page < 1) page = 1;

If this value retrieved via get is not present, then page will be NoN.

How can I make sure page is always defined as minimum 1 ?

Your getUrlParameter is returning something that is not convertible to a number NaN = Not a Number , if you share that function maybe we can debug a little bit further the root cause of your issue, in the meantime, I suggest the following validation:

var page = parseInt(getUrlParameter('page'));
if (page < 1 || isNaN(page)) page = 1;
var page_next = page + 1;

That way if your page is not a number, you default it to page 1. Hope this clears things out and helps you.

If your problem is within the if statement, the fastest solution I can think about (despite I don't approve it) is this one:

Replace :

var page = parseInt(getUrlParameter('page'));

with:

var page = +getUrlParameter("page") || 1;

if page is falsey (NaN is falsey) it will set it to 1, else to its result.

Example with fiddle:

function getUrlParameter ( param ) {
    return param === "page" ? 5 : false;
}

var page = +getUrlParameter("hello") || 1;
alert(page);

page = +getUrlParameter("page") || 1;
alert(page);

http://jsfiddle.net/51tvdsve/

In any case, you should rather try to fix your getUrlParameter function instead of trying to avoid its output, but that's just my opinion.

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