js对ajax返回数组的处理介绍

引言:
ajax异步传输,可以传输字符串,但是数组这样的数据,就不太好传递了,这个时候怎么办呢?

答案是可以通过json来处理,后台将数据数据进行json编码!

然后客户端,通过js来进行解析。

这样问题就解决了!json是一种很好的数据格式!

我做的是异步判断某堂课是否处于上课状态,会从后台接口中获取数组数据!共四堂课,

代码如下:

复制代码 代码如下:


function ajaxcheckedlessonsAction(){
        //3583 语文 8班
        //1500 语文 9班
        //2717 物理 8班
        //1612 物理 9班
        $whereLessons = array();
        $whereLessons['lessons.id IN(?)'] = array(3583, 1500, 2717, 1612);
        $daoLessons = new dao_lessons();
        $alllessons = $daoLessons->getLessons($whereLessons);
        //print_r($alllessons);exit;
        $lessonsChecked = array();
        foreach ($alllessons as $lessons) {
            if ($lessons['id'] == 3583) {
                $lessonsChecked['8yuwen'] = $this->verifyCheckedLessons($lessons['startime'], $lessons['endtime']);
            } elseif ($lessons['id'] == 1500) {
                $lessonsChecked['9yuwen'] = $this->verifyCheckedLessons($lessons['startime'], $lessons['endtime']);
            } elseif ($lessons['id'] == 2717) {
                $lessonsChecked['8wuli'] = $this->verifyCheckedLessons($lessons['startime'], $lessons['endtime']);
            } elseif ($lessons['id'] == 1612) {
                $lessonsChecked['9wuli'] = $this->verifyCheckedLessons($lessons['startime'], $lessons['endtime']);
            }
        }
        $json = json_encode($lessonsChecked);
        echo $json;
    }


接口处理数据,将数据json化,

前台对json数据进行解析

复制代码 代码如下:


//进入页面就进行的处理
        $.ajax({
            type: "POST",
            url:"/default/index/ajaxcheckedlessons",
            data:"",
            success:function(response){
                if(response){
                    var data = eval('('+response+')');
                    if(data['8yuwen']){
                      $("#8yuwen").attr("style","color:red;");
                    }else{
                      $("#8yuwen").attr("style",""); 
                    }
                    if(data['8wuli']){
                      $("#8wuli").attr("style","color:red;");
                    }else{
                      $("#8wuli").attr("style",""); 
                    }
                    if(data['9yuwen']){
                      $("#9yuwen").attr("style","color:red;");
                    }else{
                      $("#9yuwen").attr("style",""); 
                    }
                    if(data['9wuli']){
                      $("#9wuli").attr("style","color:red;");
                    }else{
                      $("#9wuli").attr("style",""); 
                    }
                }else{
                    alert("error");
                }
            }
        });


红色部分就是json的核心代码。

这样就完成了数组的处理!异步数组数据传递!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wfwgjy.html