简体   繁体   English

IF语句中的Javascript对象声明

[英]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. 基本上,我使用JQUERY / ajax来调用php脚本以验证一些输入并获取一些数据。 The returned data is encoded JSON, so i set the datatype to JSON in JQUERY and it returns an object. 返回的数据是经过编码的JSON,因此我在JQUERY中将数据类型设置为JSON,它返回一个对象。

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. 我刚刚发现,在某些(一定要说是不寻常的)情况下,网络连接没有以预期的方式响应,ajax调用会调用JQUERY中的error选项。

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. 在大多数情况下,我会从服务器返回一条错误消息,但是有时会出现错误,并且没有从服务器端脚本发送回JSON。 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. 我还没有找到导致网络状况的确切原因,但是无论如何,我认为我只是用Javascript处理它,而我还不知道。

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. 在上面的代码中,数据对象应该在“ if”语句之前存在或不存在。 And when I get to the runDialogue(); 当我进入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. 不起作用的是当“数据”对象不存在时,即if如果“ if”测试失败。 The else should create the object "data" but doesn't. else应该创建对象“ data”,但不是。

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. 您将在else块(更具体的作用域)中重新定义变量数据 ,因此全局作用域变量仍将是未定义的。 Change var data = new tempdata(); 更改var数据= new tempdata(); to

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

So, now your ajax call should look like: 因此,现在您的ajax调用应如下所示:

$.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; Javascript对未定义的引用抛出错误; 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". 您可以使用typeof运算符来测试数据是否存在,或者是否为“对象”类型。

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) 当$ .ajax失败(由于HTTP错误)时,将调用.error方法并传递以下参数: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. 因此,您称为“数据”的第一个参数不是“ Web服务器向您发送的内容”,而是一个jQuery包装的xmlhttprequest对象。 Testing it via "if" [eg if (data)] will always return true. 通过“ if” [例如if(data)]进行测试将始终返回true。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM