jQuery Ajax向某個頁面傳值並取得返回的數組

來源:互聯網
上載者:User

標籤:blog   http   java   使用   os   2014   

本案例講訴通過Ajax向某個PHP頁面傳值,並將得到的數組通過json_encode()函數處理,然後返回給ajax,下面是在實際案例摘取的部分代碼:

PHP頁面

    public function showChatName(){        $chat = A('Article','Event');        $res = $chat->selectName(I('get.channel'));        echo json_encode($res);    }

數組$res經過json_encode處理後的輸出形式

{"channel_name":"abc"}

模板頁面

    <script src="../../public/home/js/jquery.min.js"></script>    <script type="text/javascript">        //取得cookie值        function getCookie(name){            var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");            if(arr=document.cookie.match(reg)){                return unescape(arr[2]);            }else{                return null;            }        }        $(function(){            var channel = getCookie('channels');            var a = window.location.host;            $.ajax({                type:'GET', //以get方式與後台溝通                url :'http://'+a+'/Article/showChatName',//與此php頁面溝通                dataType:'json',//從php返回的值以JSON方式解釋                data:'channel='+channel,                cache:false,                success:function(msg){//如果調用php成功,注意msg是返回的對象,這個你可以自訂                    if(msg.channel_name != ''){//channel_name就是數組的一個索引值                        var b = msg.channel_name;                        $("h1").text(b);                        return false;                       }                }            });        });        </script>        <body>            <div id="headlineContainer">                <h1 id='title_h1'></h1>            </div>

使用$.cookie(‘channels‘)的時候提示:Object doesn‘t support property or method ‘cookie‘!不知道是怎麼回事,所有自己用js寫了個擷取Cookie的方法,然後直接調用。

點擊這裡下載示範版

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.