javascript 为什么我会收到此错误:“未捕获的类型错误:无法读取未定义的属性‘标题’”?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8113985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 02:21:01  来源:igfitidea点击:

Why am i getting this error: "Uncaught TypeError: Cannot read property 'Title' of undefined"?

javascriptjqueryajaxjson

提问by Matt

I am trying to write an ajaxweb app. I have a function that is suppose to request a jsonobject and then use it to re/populate the website.

我正在尝试编写一个ajax网络应用程序。我有一个函数,假设请求一个json对象,然后使用它来重新/填充网站。

Here is the Javascriptin Question (Lines 8 - 16):

这是问题中的Javascript (第 8 - 16 行)

window.onload=LoadData("Home", {});
var _doc = {};
function LoadData(page, params) {
    $.get(page, params, function ( data ) { 
        _doc = jQuery.parseJSON( data ); 
        }
    );
    document.title = _doc.Title.Title;
};

Here is the error Chromegave:

这是Chrome给出的错误:

Uncaught TypeError: Cannot read property 'Title' of undefined
LoadDatahttp://127.0.0.1/:15
(anonymous function)

This is what has me confused if I run the same statement in the console:

如果我在控制台中运行相同的语句,这让我感到困惑:

document.title = _doc.Title.Title;
"Home"

And it changes the title to Home

并将标题更改为 Home

Here is proof that its not undefined:

这是它不是未定义的证据:

_doc
Object
   Body: Object
      Menus: Array[4]
         0: Object
            Menu: Object
         1: Object
            Menu: Object
         2: Object
            Menu: Object
         3: Object
            Menu: Object
   Title: Object
      Title: "Home"
   User: Object
      Name: "Username"

And A screenshot as an overview: This is What the Chrome Console Looks Like...Note: the call to the function at the bottom did change the title

和作为概述的屏幕截图: 这就是 Chrome 控制台的样子......注意:对底部函数的调用确实改变了标题

回答by Matt

You can only access the datafrom the AJAX request in the callback:

您只能data从回调中的 AJAX 请求访问:

window.onload=LoadData("Home", {});
var _doc = {};
function LoadData(page, params) {
    $.get(page, params, function ( data ) { 
          _doc = jQuery.parseJSON( data ); 
          document.title = _doc.Title.Title;
        }
    ));
};

AJAX requests (AsynchronousJavaScript and XML) requests are asynchronous; the browser initiates the request, and does notwait for a response... instead the JavaScript execution is continued. Some time later, when the HTTP request for the AJAX request has completed, the callback you provided for the AJAX request is invoked, and has access to the data contained in the HTTP response.

AJAX 请求(异步JavaScript 和 XML)请求是异步的;浏览器发起请求,等待响应……而是继续执行 JavaScript。一段时间后,当 AJAX 请求的 HTTP 请求完成时,您为 AJAX 请求提供的回调被调用,并且可以访问 HTTP 响应中包含的数据。

In your situation, document.title = _doc.Title.Title;is executed immediatelyafter the AJAX request is dispatched (i.e. before the some time latermentioned above has occured); so the callback _doc = jQuery.parseJSON( data );has not fired yet, so _docis still an empty object, so _doc.Titleis undefined, and trying to retrieve Titleon the undefined _doc.Titleis throwing the error.

在您的情况下,在发送 AJAX 请求后立即document.title = _doc.Title.Title;执行(即在上面提到的某个时间之前发生);所以回调还没有解雇呢,所以仍然是一个空的对象,所以是不确定的,并试图找回在未定义抛出的错误。_doc = jQuery.parseJSON( data );_doc_doc.TitleTitle_doc.Title

Unrelated to your problem, but FYI, you might want to look at the jQuery.getJSONmethod; the difference between that that the jQuery.getmethod is that the response object you get passed will alreadybe the JSON object (so you won't need to call jQuery.parseJSON).

与您的问题无关,但仅供参考,您可能想查看该jQuery.getJSON方法;与该jQuery.get方法之间的区别在于,您传递的响应对象已经是 JSON 对象(因此您不需要调用jQuery.parseJSON)。

回答by jfriend00

Your $.get()function is asynchronous. That means that when you call it, all you are doing is STARTING the execution of the ajax call. Thus, the line following it:

你的$.get()函数是异步的。这意味着当您调用它时,您所做的只是开始执行 ajax 调用。因此,跟随它的行:

document.title = _doc.Title.Title;

is executing BEFORE the ajax call has completed. You only know the ajax call has completed in it's completion function.

在 ajax 调用完成之前执行。你只知道 ajax 调用已经在它的完成函数中完成了。

To fix this, put the reference to _docin the ajax completion function:

要解决此问题,请_doc在 ajax 完成函数中添加对的引用:

window.onload=LoadData("Home", {});
var _doc = {};
function LoadData(page, params) {
    $.get(page, params, function ( data ) { 
        _doc = jQuery.parseJSON( data ); 
        document.title = _doc.Title.Title;
        }
    );
};