zoukankan      html  css  js  c++  java
  • Ajax和Jsonp实践

    之前一直使用jQuery的ajax方法,导致自己对浏览器原生的XMLHttpRequest对象不是很熟悉,于是决定自己写下,以下是个人写的deom,发表一下,聊表纪念。

    Ajax 和 jsonp 的javascript 实现:

    /*! 
    * ajax.js
    * © auth zernmal 
    * @ description XMLHttpRequest and Jsonp practice
    */
    
    function ajax(url,options ){
        
        var options = options || {} ,
            method = options.method || "GET",
            async = (typeof options.async !== "undefined") ? options.async : true ,
            user = (typeof options.user !== "undefined") ? options.user : "" ,
            pswd = (typeof options.pswd !== "undefined") ? options.pswd : "" ,
            reciveType = options.reciveType || "string" ,
            data = options.data || null ,
            header = options.header || [],
            callback = options.callback || function(){},
            xhr =  XMLHttpRequest ?  new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    
        if(method=='GET' && data){
            
            var dataStr = [];
    
            url = (url.indexOf("?")==-1) ? url + "?" : url + "&" ; 
    
            for(var i in data){
                dataStr.push( i + "=" + data[i]) ;
            }
            url += dataStr.join("&");
            data = null;
        }else if(data){
            var form = new FormData();        
            for(var i in data){
                form.append( i , data[i]);    
            }
            data = form;
        }
    
        xhr.onreadystatechange = function() {
        
            if (xhr.readyState == 4) {// 4 = "loaded"
                if (xhr.status == 200) {// 200 = OK
                    
                    var responseData = null ;
    
                    if(reciveType==="string"){
                        responseData = xhr.responseText;
                    }else if(reciveType === "json"){
                        responseData = xhr.responseText;
                        
                        if( false && JSON && JSON.parse) {
                            responseData = JSON.parse(responseData);
                        }else{
                            responseData = eval('('+responseData+')');
                        }
                    }
    
                    options.callback && options.callback(responseData);
                } else {
                    alert("Problem retrieving XML data");
                }
            }
        };
        
        xhr.open(method , url , async , user ,pswd);    
        
        for(var i = header.length -1 ; i > 0 ; i--){
            xhr.setRequestHeader(header[i].type, header[i].content);    
        }
    
        xhr.send(data);
    }
    
    function jsonp(url , options){
        var options = options || {} ,
            script = document.createElement('script') ,
            callback = options.callback || function(result){} ,
            callbackName = 'myjsonpcall'+ (new Date()).getTime(),
            data = options.data || {} ,
            dataStr = [];
        
    
        for(var i in data){
            dataStr.push( i + "=" + data[i]) ;
        }
    
        if(url.indexOf("?")==-1){
            url += "?"+ dataStr.join("&") +"&callback="+callbackName;
        }else{
            url += "&"+ dataStr.join("&") +"&callback="+callbackName;
        }
    
        script.setAttribute('src', url);    
        window[callbackName] = callback ;
    
        // 把script标签加入head,此时调用开始
        document.getElementsByTagName('head')[0].appendChild(script);
    }

    PHP服务端响应请求:

    <?php
    
        $func = $_GET['func'];
    
        if(function_exists($func)){
            $func();
        }else{
            funcNotExist();
        }
    
        function funcNotExist(){
            echo "function is not exist ! ";
        }
    
        function returnJson(){
            $lastName = $_GET['lastName'];
            $firstName = $_GET['firstName'];
    
            echo json_encode(array('firstName'=>$firstName,'lastName'=>$lastName));
        }
    
        function returnString(){
            $lastName = $_GET['lastName'];
            $firstName = $_GET['firstName'];
            echo "the string you send is ".$lastName." ".$firstName;
        }
    
        function postReturn(){
            $lastName = $_POST['lastName'];
            $firstName = $_POST['firstName'];
            echo "the string you post is ".$lastName." ".$firstName;
        }
    
        function jsonP(){
    
            header('content-type: application/json; charset=utf-8');
            $lastName = $_GET['lastName'];
            $firstName = $_GET['firstName'];
            $callbackFunc = isset($_GET['callback'])? htmlspecialchars($_GET['callback']):"callback";
            $json = json_encode(array('firstName'=>$firstName,'lastName'=>$lastName));
    
            echo "$callbackFunc($json)";
        }

    页面内调用方法:

    <!DOCTYPE html>
    <html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Ajax与Jsonp实践</title>
        <script type="text/javascript" src="js/ajax.js"></script>
    </head>
    <body>
    <script>
        jsonp("/ajax.php?func=jsonP",{
        callback : function(result){
            console.log(result);
        },
        data : {
            lastName : "zernmal" , 
            firstName : "chen"
        } 
    });
    
    
    ajax("/ajax.php?func=returnJson",{
        method : "GET",
        callback : function(result){
            console.log(result);
        },
        data : {
            lastName : "zernmal" , 
            firstName : "chen"
        } ,
        reciveType : "json"
    });
    </script>
    </body>
    </html>

    以上只是简单实验,如有问题欢迎提出。

    本文为原创文章,转载请注明出处:http://www.cnblogs.com/zernmal/
  • 相关阅读:
    According to TLD or attribute directive in tag file, attribute end does not accept any expressions
    Several ports (8080, 8009) required by Tomcat v6.0 Server at localhost are already in use.
    sql注入漏洞
    Servlet—简单的管理系统
    ServletContext与网站计数器
    VS2010+ICE3.5运行官方demo报错----std::bad_alloc
    java 使用相对路径读取文件
    shell编程 if 注意事项
    Ubuntu12.04下eclipse提示框黑色背景色的修改方法
    解决Ubuntu环境变量错误导致无法正常登录
  • 原文地址:https://www.cnblogs.com/zernmal/p/3751066.html
Copyright © 2011-2022 走看看