Javascript updating global variables and hoisting

I have a javascript function that uses an ajax function to post to a php script and a variable used to determine if the result comes back as true or false. In php, I would normally assign the function to a variable such as this:

$insert_item = $process->insert_item($item_array);

If ($insert_item->error)
{
//error detected, do something
}

I have not been able to accomplish this with javascript. Instead, I get a [object object] return if I assign a function to a variable. As a cheap alternative, I am trying to use a global variable to write any errors:

var error = false;

function update_db(formInput) {
    $.post(action.php, formInput, function(data) {

        if (data != 0) {

            error = true

        }
    });

    return error;
}

var updateDb = update_db(form_data);

if (updateDb) {

    alert("error detected");

In this example, 'error' comes back as false despite the ajax function updating it to true. I have read all about javascript hoisting, but have yet to find a solution. Is there anyway around this? My problem stems completely from the ajax function which I have also tried accessing directly to return any vars (like I easily do in PHP) but I have had no luck!

As a side note, I find it interesting that I can access 'error' within the ajax function (returns as false) but not able to change it.

链接地址: http://www.djcxy.com/p/96304.html

上一篇: Javascript提升和变量赋值(没有声明)

下一篇: Javascript更新全局变量和提升