IF 语句中的 Javascript 对象声明

发布于 2024-10-31 09:36:51 字数 1455 浏览 1 评论 0原文

我对这个标题感到抱歉,我只是不知道如何描述这个标题。

基本上我使用 JQUERY/ajax 调用 php 脚本来验证一些输入并获取一些数据。返回的数据是编码的JSON,所以我在JQUERY中将数据类型设置为JSON,它返回一个对象。

我刚刚发现,在某些(必须说是不寻常的)网络连接未按预期方式响应的情况下,ajax 调用会调用 JQUERY 中的错误选项。

在大多数情况下,我都会收到从服务器返回的错误消息,但有时会出现错误,并且服务器端脚本没有发回任何 JSON。我还没有确切地查明是什么会引发这种网络情况,但无论如何,我认为我应该在 Javascript 中处理它,尽管我还不知道。

这个想法是检查是否已创建预期的对象,如果没有,则使用两个预期的属性创建它并运行对话。这样我就可以避免重复编写错误消息。虽然节省的不多,但我想尝试一下其中的原理。

 $.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

在上面的代码中,数据对象应该在“if”语句之前存在或不存在。当我到达 runDialogue(); 时对象数据应始终存在,以便传递 errortitle 和 errordescription 属性。

当“数据”对象存在时,就没有问题。不起作用的是当“数据”对象不存在时,即如果未通过“if”测试。 else 应该创建对象“data”,但没有。

我做错了什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

雪花飘飘的天空 2024-11-07 09:36:51

您正在 else 块(更具体的范围)中重新定义变量data,因此全局范围变量仍然是未定义的。
更改 var data = new tempdata();那么

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

,现在您的 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

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
感性不性感 2024-11-07 09:36:51

JavaScript 对未定义的引用抛出错误;你不能仅使用对象来测试存在性。您可以使用 typeof 运算符来测试数据是否存在,或者是否为“object”类型。

例如:

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);
}

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);
}
人间☆小暴躁 2024-11-07 09:36:51

当 $.ajax 失败(由于 HTTP 错误)时,将调用 .error 方法并传递以下参数:
error(jqXHR, textStatus, errorThrown)

因此,您称为“数据”的第一个参数不是“网络服务器发送给您的内容”,而是一个 jquery 包装的 xmlhttprequest 对象。通过“if”[例如 if (data)] 测试它将始终返回 true。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文