Var becomes NaN after fixing at 10 in function

var post = 10;
function load_more(str) {
        var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("add").innerHTML = document.getElementById("add").innerHTML + xmlhttp.responseText;
            }
        };
        var post = post + 10;
        xmlhttp.open("GET", "fetch_more.php?number=" + post , true);
        xmlhttp.send();
}

When I load the website, I expect the browser to determine the value 10 for publication and do nothing until I press the button that calls the load_more () function, which increments this value by 10 and passes it to PHP via Ajax.

The desired behavior is to have 10 posts on the site, and then click 10 clicks on the button each time the button is clicked.

But PHP just throws a MySQL error, and the log shows that post var is NaN.

+4
source share
4 answers

Line

var post = post + 10;

is the culprit. Javascript has hoisting behavior , which essentially means that your variables are always declared at the top of the scope.

, :

var post = 10;
function load_more(str) {
    var post; // `post` is now undefined
    //...other code
    post = post + 10; // undefined + 10 evaluates to NaN
}

, , , post , post undefined, post + 10, post = post + 10 NaN ( undefined + 10 NaN).

, var :

post = post + 10;

post += 10;
+7

var .

post += 10; .

+1

, var . , + 10. undefined, "var post = undefined + 10", NaN

0
source

use post += 10orpost = post + 10

Uninstall inside your function var. It hides a variable postdeclared outside the function.

0
source

Source: https://habr.com/ru/post/1622538/


All Articles