DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> AJAX入門 >> AJAX基礎知識 >> js對ajax返回數組的處理介紹
js對ajax返回數組的處理介紹
編輯: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的核心代碼。

這樣就完成了數組的處理!異步數組數據傳遞!

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved