http://192.168.66.90:8080/php/Ajax_.php?callback=
PHP代码
- <?php
- //公共声明
- header('Content-type: text/json');
- html_entity_decode($string, ENT_QUOTES, 'UTF-8');
- //回调参数设置
- $param="callback";
- $callback=$_REQUEST[$param];
- //自造Json数据
- $str2='[{"id":"1","name":"测试1"},{"id":"2","name":"测试2"}]';
- $str=$callback."(".$str2.")";
- //判断请求参数存在就会输出Json数据
- //if(isset($callback)&&!empty($callback)){
- if(isset($callback)){
- if (isset($_POST["mail"])&&!emptyempty($_POST["mail"])){
- echo "1";
- }else{
- //echo "N0, mail is not set";
- echo $str;
- }
- }
- //判断请求参数不存在就输出错误信息
- if(!isset($callback)){
- header("Content-type: text/html; charset=utf-8");
- $str="<h1>400 Required String parameter '{$param}' is not present</h1><hr /><small>http Request with error params: none callback function</small>";
- echo $str;
- //strip_tags() 函数剥去 HTML、XML 以及 PHP 的标签
- //echo strip_tags($str);
- }
- ?>
http://192.168.66.90:8080/html/test/js_Ajax.html
XML/HTML代码
- <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>无标题文档</title>
- </head>
- <body>
- <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"/>
- <div style=" width:100%; background:#000; color:#fff; text-align:center; font-size:6em; cursor:pointer; padding:0.2em;" id="html">点击事件</div>
- <script type="text/javascript">
- /**
- * 复杂的ajax封装
- * @version 1.0
- *
- * 用法
- * var xmlhttp = new YAjax();
- * xmlhttp.request({
- * url : "./demo.php", // get请求时 可以这样写 "./demo.php?name=zhangsan"
- * method : "POST",
- * data : "name=李四", // 支持json传值 {"name":"zhangsan"} get时不用该参数
- * receiveType : "html", // json html or xml
- * timeout : 3000, // 3秒
- * success : function(d) {alert(d);},
- * error : function(xmlhttp){alert('timeout');}
- * });
- *
- */
- function YAjax() {
- thisthis._self = this;
- thisthis.xmlhttp = this.init();
- }
- YAjax.prototype = {
- constructor : YAjax,
- // 初始化xmlhttpRequest
- init : function() {
- var xmlhttp = null;
- // 针对不同浏览器建立这个对象的不同方式写不同代码
- if(window.XMLHttpRequest) {
- xmlhttp = new XMLHttpRequest();
- //针对某些特定版本的Mozillar浏览器的BUG进行修正
- if(xmlhttp.overrideMimeType) {
- xmlhttp.overrideMimeType("text/xml");
- }
- } else if (window.ActiveXObject) {
- var activexName = ['MSXML2.XMLHTTP', 'Microsoft.XMLHTTP'];
- for (var i=0; i<activexName.length; i++) {
- try {
- xmlhttp = new ActiveXObject(activexName[i]);
- break;
- } catch(e) {}
- }
- }
- return xmlhttp;
- },
- extend : function(destination, source, override) {
- if(undefined == override) override = true;
- if(typeof destination != "object" && typeof destination != "function") {
- if(!override)
- return destination;
- else
- destination = {};
- }
- var property = '';
- for(property in source) {
- if(override || !(property in destination)) {
- destination[property] = source[property];
- }
- }
- return destination;
- },
- // json to string {name: 'lisi', age: 10} --> name=lisi&age=10
- json2String : function(jsonData) {
- var strArr = [];
- for(var k in jsonData) {
- strArr.push(k + "=" + jsonData[k]);
- }
- return strArr.join("&");
- },
- // 发送http 请求
- request : function(opt) {
- var _self = this,
- isTimeout = false,
- timeFlag = 0,
- options = {
- url : "", // string
- data : "", // json or string
- method : "POST",
- receiveType : "html", // html json or xml
- timeout : 7000,
- async : true,
- success : function(){alert("define your success function");},
- error : function(xmlhttp){}
- };
- if("data" in opt) {
- if(typeof opt.data == "string"){} else {opt.data = this.json2String(opt.data); }
- }
- options = this.extend(options, opt);
- this.xmlhttp.onreadystatechange = function(){
- if(_self.xmlhttp.readyState == 4) {
- if(!isTimeout && _self.xmlhttp.status == 200) {
- clearTimeout(timeFlag);
- var t = options.receiveType.toLowerCase();
- if(t == "html") {
- options.success(_self.xmlhttp.responseText);
- } else if(t == "xml") {
- options.success(_self.xmlhttp.responseXML);
- } else if(t == 'json') {
- try {
- var obj = JSON.parse(_self.xmlhttp.responseText);
- options.success(obj);
- } catch(e) {
- var str = '(' + _self.xmlhttp.responseText + ')'; //json字符串
- options.success(eval(str));
- }
- } else {}
- } else {
- clearTimeout(timeFlag);
- options.error(_self.xmlhttp);
- }
- }
- };
- timeFlag = setTimeout(function(){
- if(_self.xmlhttp.readyState != 4) {
- isTimeout = true;
- _self.xmlhttp.abort();
- clearTimeout(timeFlag);
- }
- }, options.timeout);
- this.xmlhttp.open(options.method.toUpperCase(), options.url, options.async); //打开与服务器连接
- if(options.method.toUpperCase() == "POST") {
- this.xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); //post方式要设置请求类型
- this.xmlhttp.send(options.data); //发送内容到服务器
- } else {
- this.xmlhttp.send(null);
- }
- }
- };
- var text=document.getElementById("input").value;
- var html=document.getElementById("html");
- html.onclick=function(){
- var xmlhttp = new YAjax();
- xmlhttp.request({
- url:"http://192.168.66.90:8080/php/Ajax_.php?callback=", // get请求时 可以这样写 "./demo.php?name=zhangsan"
- method:"POST",
- data:{"mail":"zhangsan@163.com"}, // 支持json传值 {"name":"zhangsan"} get时不用该参数 "name=李四"
- receiveType:"json", // json html or xml
- timeout:3000, // 3秒
- success:function(data){
- //JSON.stringify(data); //可以将json对象转换成json对符串
- //JSON.parse(jsonstr); //可以将json字符串转换成json对象
- if(data==1){
- alert("传参已被服务器接收,"+"输入框内容:"+text)
- }
- else{
- alert(JSON.stringify(data[0].name));
- }
- },
- error:function(xmlhttp){alert('timeout');}
- });
- };
- </script>
- </body>
- </html>