http://192.168.66.90:8080/php/Ajax_.php?callback=

PHP代码
  1. <?php  
  2. //公共声明  
  3. header('Content-type: text/json');  
  4. html_entity_decode($string, ENT_QUOTES, 'UTF-8');  
  5.   
  6. //回调参数设置  
  7. $param="callback";  
  8. $callback=$_REQUEST[$param];  
  9.   
  10. //自造Json数据  
  11. $str2='[{"id":"1","name":"测试1"},{"id":"2","name":"测试2"}]';  
  12. $str=$callback."(".$str2.")";  
  13.   
  14.   
  15. //判断请求参数存在就会输出Json数据  
  16. //if(isset($callback)&&!empty($callback)){  
  17. if(isset($callback)){  
  18.     if (isset($_POST["mail"])&&!emptyempty($_POST["mail"])){  
  19.         echo "1";      
  20.     }else{    
  21.         //echo "N0, mail is not set";  
  22.         echo $str;  
  23.     }  
  24. }  
  25.   
  26. //判断请求参数不存在就输出错误信息  
  27. if(!isset($callback)){  
  28. header("Content-type: text/html; charset=utf-8");  
  29. $str="<h1>400 Required String parameter '{$param}' is not present</h1><hr /><small>http Request with error params: none callback function</small>";  
  30. echo $str;  
  31. //strip_tags() 函数剥去 HTML、XML 以及 PHP 的标签  
  32. //echo strip_tags($str);  
  33. }  
  34.   
  35. ?>  

http://192.168.66.90:8080/html/test/js_Ajax.html

XML/HTML代码
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  2. <html xmlns="http://www.w3.org/1999/xhtml">  
  3. <head>  
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
  5. <title>无标题文档</title>  
  6.   
  7. </head>  
  8.   
  9. <body>  
  10. <input value="张三" type="text" style="width:96%; background: #F1F1ED; color:#000; text-align:center; font-size:6em; padding:0.2em; margin-bottom:0.5em; border:0.1em #333 solid " id="input"/>  
  11. <div style=" width:100%; background:#000; color:#fff; text-align:center; font-size:6em; cursor:pointer; padding:0.2em;" id="html">点击事件</div>  
  12. <script type="text/javascript">  
  13. /**  
  14. * 复杂的ajax封装  
  15. * @version 1.0  
  16. *  
  17. * 用法  
  18. *  var xmlhttp = new YAjax();  
  19. *    xmlhttp.request({  
  20. *         url : "./demo.php",  // get请求时 可以这样写 "./demo.php?name=zhangsan"  
  21. *        method : "POST",  
  22. *        data : "name=李四",  // 支持json传值 {"name":"zhangsan"}  get时不用该参数  
  23. *        receiveType : "html",  // json html or xml  
  24. *        timeout : 3000,  // 3秒  
  25. *        success : function(d) {alert(d);},  
  26. *        error : function(xmlhttp){alert('timeout');}  
  27. *    });  
  28. *  
  29. */  
  30. function YAjax() {  
  31.     thisthis._self = this;  
  32.     thisthis.xmlhttp = this.init();  
  33. }  
  34. YAjax.prototype = {  
  35.     constructor : YAjax,  
  36.       
  37.     // 初始化xmlhttpRequest  
  38.     init : function() {  
  39.         var xmlhttp = null;  
  40.       
  41.         // 针对不同浏览器建立这个对象的不同方式写不同代码  
  42.         if(window.XMLHttpRequest) {  
  43.             xmlhttp = new XMLHttpRequest();  
  44.             //针对某些特定版本的Mozillar浏览器的BUG进行修正  
  45.             if(xmlhttp.overrideMimeType) {  
  46.                 xmlhttp.overrideMimeType("text/xml");  
  47.             }  
  48.               
  49.         } else if (window.ActiveXObject) {  
  50.             var activexName = ['MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];  
  51.             for (var i=0; i<activexName.length; i++) {  
  52.                 try {  
  53.                     xmlhttp = new ActiveXObject(activexName[i]);  
  54.                     break;  
  55.                 } catch(e) {}  
  56.             }  
  57.         }  
  58.       
  59.         return xmlhttp;  
  60.     },  
  61.       
  62.     extend : function(destination, source, override) {  
  63.         if(undefined == override) override = true;  
  64.         if(typeof destination != "object" && typeof destination != "function") {  
  65.             if(!override)  
  66.                 return destination;  
  67.             else  
  68.                 destination = {};  
  69.         }  
  70.         var property = '';  
  71.         for(property in source) {  
  72.             if(override || !(property in destination)) {  
  73.                 destination[property] = source[property];  
  74.             }  
  75.         }  
  76.       
  77.         return destination;      
  78.     },  
  79.       
  80.     // json to string {name: 'lisi', age: 10} --> name=lisi&age=10  
  81.     json2String : function(jsonData) {  
  82.         var strArr = [];  
  83.         for(var k in jsonData) {  
  84.             strArr.push(k + "=" + jsonData[k]);      
  85.         }  
  86.               
  87.         return strArr.join("&");  
  88.     },  
  89.       
  90.     // 发送http 请求  
  91.     request : function(opt) {  
  92.         var _self = this,  
  93.             isTimeout = false,  
  94.             timeFlag = 0,  
  95.             options = {  
  96.                 url : "",   // string  
  97.                 data : "",  // json or string  
  98.                 method : "POST",  
  99.                 receiveType : "html",  // html json or xml  
  100.                 timeout : 7000,  
  101.                 async : true,  
  102.                 success : function(){alert("define your success function");},  
  103.                 error : function(xmlhttp){}  
  104.             };  
  105.         if("data" in opt) {  
  106.             if(typeof opt.data == "string"){} else {opt.data = this.json2String(opt.data); }      
  107.         }  
  108.         options = this.extend(options, opt);  
  109.           
  110.         this.xmlhttp.onreadystatechange = function(){  
  111.             if(_self.xmlhttp.readyState == 4) {  
  112.                 if(!isTimeout && _self.xmlhttp.status == 200) {  
  113.                     clearTimeout(timeFlag);  
  114.                     var t = options.receiveType.toLowerCase();  
  115.                     if(t == "html") {  
  116.                         options.success(_self.xmlhttp.responseText);  
  117.                           
  118.                     } else if(t == "xml") {  
  119.                         options.success(_self.xmlhttp.responseXML);      
  120.                           
  121.                     } else if(t == 'json') {  
  122.                         try {  
  123.                             var obj = JSON.parse(_self.xmlhttp.responseText);  
  124.                             options.success(obj);      
  125.                         } catch(e) {  
  126.                             var str = '(' + _self.xmlhttp.responseText + ')';  //json字符串  
  127.                             options.success(eval(str));  
  128.                         }  
  129.                     } else {}  
  130.                       
  131.                 } else {  
  132.                     clearTimeout(timeFlag);  
  133.                     options.error(_self.xmlhttp);  
  134.                 }  
  135.             }  
  136.         };  
  137.           
  138.         timeFlag = setTimeout(function(){  
  139.             if(_self.xmlhttp.readyState != 4) {  
  140.                 isTimeout = true;  
  141.                 _self.xmlhttp.abort();  
  142.                 clearTimeout(timeFlag);  
  143.              }      
  144.         }, options.timeout);  
  145.           
  146.         this.xmlhttp.open(options.method.toUpperCase(), options.url, options.async);  //打开与服务器连接  
  147.         if(options.method.toUpperCase() == "POST") {  
  148.             this.xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');  //post方式要设置请求类型  
  149.             this.xmlhttp.send(options.data);  //发送内容到服务器  
  150.         } else {  
  151.                 this.xmlhttp.send(null);  
  152.         }  
  153.     }  
  154. };  
  155.   
  156. var text=document.getElementById("input").value;  
  157. var html=document.getElementById("html");  
  158. html.onclick=function(){  
  159.   
  160. var xmlhttp = new YAjax();  
  161.   xmlhttp.request({  
  162.        url:"http://192.168.66.90:8080/php/Ajax_.php?callback=",  // get请求时 可以这样写 "./demo.php?name=zhangsan"  
  163.        method:"POST",  
  164.        data:{"mail":"zhangsan@163.com"},  // 支持json传值 {"name":"zhangsan"}  get时不用该参数 "name=李四"  
  165.        receiveType:"json",  // json html or xml  
  166.        timeout:3000,  // 3秒  
  167.        success:function(data){  
  168.        //JSON.stringify(data); //可以将json对象转换成json对符串  
  169.        //JSON.parse(jsonstr); //可以将json字符串转换成json对象  
  170.            if(data==1){  
  171.             alert("传参已被服务器接收,"+"输入框内容:"+text)  
  172.            }  
  173.            else{  
  174.             alert(JSON.stringify(data[0].name));  
  175.            }  
  176.        },  
  177.        error:function(xmlhttp){alert('timeout');}  
  178.    });  
  179. };  
  180. </script>  
  181. </body>  
  182. </html>  

 

PHP/Java | 评论(0) | 引用(0) | 阅读(2651)