【问题标题】:Global js var unreadable in jQuery + $.ajax全局 js var 在 jQuery + $.ajax 中不可读
【发布时间】:2013-07-13 01:32:18
【问题描述】:

早上好,

我试图在 .ready() 之前填充一个名为 statusJson 的全局变量,但由于某种原因可以使用 chrome 控制台调试访问和读取该变量,但脚本无法读取该变量。

代码:http://jsfiddle.net/wiitohzjeh/pEKyT/

可以看到,json信息是通过$.ajax从远程php文件中获取的,我创建了一个模拟ajax-json响应的var,并注释了原始$.ajax代码。

问题: 由于某种原因,chrome 调试控制台返回 Uncaught TypeError: Cannot read property '0' of undefined

谢谢大家:)

【问题讨论】:

    标签: jquery json var populate


    【解决方案1】:

    您需要将 JSON 解析为对象

    以下替换:

    statusJson = ajaxData;
    

    statusJson = $.parseJSON(ajaxData);
    

    并在Status 定义之后移动$(function(){ Status.init(); });

    Updated Fiddle

    【讨论】:

    • 响应来解析,我想。原代码是这样的:pastebin.com/raw.php?i=AVLkfwEz,按你说的修改,答案是一样的Uncaught TypeError: Cannot read property '0' of undefined
    • 如你所说,已更新。仍然没有工作:jsfiddle.net/wiitohzjeh/pEKyT/2Uncaught TypeError: Cannot read property '0' of undefined line :15
    • ajax call to statusjson.php 在 jsFiddle 中不起作用。在本地测试并确保来自statusjson.php 的响应为JSON 格式
    • 是 JSON,header("Content-type: application/json");
    • 试试echo json_encode($response_data);echo '{"status":["ok","allwork"],"statuses":{"login":true},"stream":{"1373877245":{"title":"asjdhfgjqwherh"}}}';
    【解决方案2】:

    你的代码的关闭示例我的朋友:

    var statusJson = {};
    
    var Status =  new (function(){     
    
        // public function //
        function init(){        
        // this is the data returned by $.ajax:
        var ajaxData = '{"status":["ok","allwork"],"statuses":{"login":true},"stream":{"1373877245":{"title":"asjdhfgjqwherh"}}}';
            statusJson = $.parseJSON(ajaxData);
            this.updateHeader();  
        };
    
        // private function //
        function updateHeader(){
            $(".status-header span")
                .fadeOut()
                .addClass(statusJson.status[0])
                .text(statusJson.status[1])
                .fadeIn();
        };
    
        // return the PUBLIC functions //
        return {
            init: init
         };
    })();
    
    Status.init();
    

    【讨论】:

    • 不,Uncaught TypeError: Object #<Object> has no method 'updateHeader' 无法加载 updateHeader(),与 Status.updateHeader 相同
    猜你喜欢
    • 2018-06-05
    • 2019-11-22
    • 2016-11-08
    • 2017-11-02
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多