开发者

Javascript object declaration in IF statement

I'm sorry about the title I'm just not sure how to describe this one.

Basically I'开发者_如何转开发m using JQUERY/ajax to invoke a php script to validate some input and get some data. The returned data is encoded JSON, so i set the datatype to JSON in JQUERY and it returns an object.

I have just discovered that under certain (it has to be said unusual) conditions where a network connection is not responding in an expected way, the ajax call invokes the error option in JQUERY.

In most cases I have an error message coming back from the server, but sometimes the error is reached and no JSON has been sent back from the server side script. I haven't tracked down exactly what can provoke that network situation yet, but in any case I thought I'd just deal with it back in Javascript whilst I don't yet know.

The idea was to check to see if the expected object had been created, and if not then create it with the two expected properties and run a dialogue. This way I'd avoid repeating writing the error messages. It's not a big saving, but I wanted to try the principle.

 $.ajax({
      url: 'getmetadata.php',
      type: "POST",
      data: entereddata,
      dataType: "json",
      timeout: (7000), //wait 7 seconds

        error: function(data) 
        {   
        // handle errors
        if(data)
        {

        // Do nothing error message will be issued from the data object 
        }else{
                    // no message was returned. Some other error occured.
            function tempdata()
            { 

                this.errortitle   = "Error title";
                this.errormessage = "Error text";
            };

            var data = new tempdata();
        };  

        // issue error message
        runDialogue(data.errortitle,data.errormessage);

        }, //ERROR

        success: function(data) 
        {
        }; // SUCCESS
}); // AJAX

in the code above, the data object should either exist or not before the "if" statement. And when I get to the runDialogue(); the object data should always exist in order to pass the errortitle and errordescription properties.

When the "data" object exists, there is no problem. What isn't working is when the "data" object does not exist, ie if fails the "if" test. The else should create the object "data" but doesn't.

What have i done wrong?


You are redefining the variable data in your else block(more specific scope) and hence the global scope variable will still be undefined. Change var data = new tempdata(); to

data = new tempdata(); //In the else block

So, now your ajax call should look like:

$.ajax({
          url: 'getmetadata.php',
          type: "POST",
          data: entereddata,
          dataType: "json",
          timeout: (7000), //wait 7 seconds

            error: function(data) 
            {   
            // handle errors
            if(data)
            {

            // Do nothing error message will be issued from the data object 
            }else{


                /******************NOTE THE CHANGE HERE********************/
                data = { 

                    errortitle:"Error title",
                    errormessage:"Error text"
                };

            };  

            // issue error message
            runDialogue(data.errortitle,data.errormessage);

            }, //ERROR

            success: function(data) 
            {
            }; // SUCCESS
    }); // AJAX


Javascript throws an error on undefined references; you can't test existence just using the object. You can use the typeof operator to test whether the data exists, or instead whether it is of type "object".

For example:

if (typeof data === "undefined")
{
   // You don't really need a closure for this...
   errordata = {'errortitle'   : 'Error Title',
                'errormessage' : 'Error Message'};

 runDialogue(data.errortitle, data.errormessage);
}


When $.ajax fails (because of a HTTP error), the .error method is called and passed the following params: error(jqXHR, textStatus, errorThrown)

So the first parameter, which you have called "data", is not "what the webserver sent you" but a jquery wrapped xmlhttprequest object. Testing it via "if" [eg if (data)] will always return true.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜