Pregunta

So I found this good example of long-polling, but I couldn't figure out how to transfer variables through it. This is what I came up with, but it doesn't work. I'm pretty confident the issue is with the dataString and type, because that's the part of the code I modified.

$(".post").each(function() {
    poll("somestuff");
});


(function poll(pid) {
    var dataString = 'pid=' + pid;
    $.ajax({
        type: 'GET',
        url: 'http://localhost:8888/site/execs/something.php',
        data: dataString,
        success: function(data) {

            alert('stuff');


        },
        dataType: "json",
        complete: poll,
        timeout: 30000
    });
})();​

Can someone tell me what it is I'm doing wrong here? Any help is appreciated, thank you.

¿Fue útil?

Solución

Regarding the scope of poll, hegemon's answer is mostly correct – the function is not global. However, there's more to it.

The way you've written poll makes it what's known as a named function expression.

Remember that there are two ways of writing functions in JavaScript. The traditional function declaration:

function foo() {
    ...
}

Declarations must be named, and are hoisted to the top (basically, parsed before any instructions are executed). Alternatively, function expressions:

var foo = function() {
    ...
}

Or

$.ajax('/', function() {
    // this is what's known as an anonymous callback
});

Or

(function() {
    // this is called a self-executing function...
})(); // <-- because we call it immediately

Expressions are executed like any other code; they are not hoisted.

And now the fun part: function expressions may be given an optional name, but that name is not accessible outside the scope of the function itself. In other words,

(function foo() {
    // `foo` is this function
});

// `foo` will be undefined here

Would be much like writing this:

(function () {
    var foo = arguments.callee; // never do this
    // `foo` is this function
});

// `foo` will be undefined here

Because of the fact that a named function expression can only call itself (or be called by a function declared inside its scope), plus a whole host of browser bugs, named function expressions are virtually useless outside of adding some context in a debugger or profiler.


So now let's walk through your code.

First, you walk through each element that has a post class. jQuery immediately invokes your anonymous callback for each matching element. You try to call poll, but it:

  1. Doesn't exist yet because function expressions are not hoisted; the poll code has not run yet.
  2. Even if it had already run (say, if you moved the $.each call to the bottom), post would still be undefined because poll is a named function expression, and we just learned that those identifiers are only available inside of the function itself.

Next, you have a self-executing function. (The () on the very last line.) In other words, poll is invoked immediately with no arguments. You're probably seeing a single long-poll sending pid=undefined.

Bonus: The complete callback (to begin a new long-poll after one times out or gets data) does work as expected, since poll is properly in scope at that point.

Fixing all this nonsense is as easy as removing three characters. Hopefully, by this point you're able to figure out which three characters those are. (Hint: make your expression a declaration.)

Otros consejos

You poll() function never gets registered in the global scope. That's becouse it is enclosed by "(...)()" construct which basically means: call "..." with no arguments and forget.

Bit late to answer perhaps...

Scope issue aside, your poll function isn't polling. It's only an ajax request.

To make it poll you need to call setTimeout. So your code would look like:

(function poll(pid) {
    var dataString = 'pid=' + pid;
    setTimeout(function() {
        $.ajax({
            type: 'GET',
            url: 'http://localhost:8888/site/execs/something.php',
            data: dataString,
            success: function(data) {

                alert('stuff');


            },
            dataType: "json",
            complete: poll,
            timeout: 30000
        });
    })
})();
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top