`
seasky332
  • 浏览: 6212 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

jquery相关总结

阅读更多
jquery相关总结



一、简介

1.1、概述
随着WEB2.0及ajax思想在互联网上的快速发展传播,陆续出现了一些优秀的Js框架,其中比较著名的有Prototype、YUI、jQuery、mootools、Bindows以及国内的JSVM框架等,通过将这些JS框架应用到我们的项目中能够使程序员从设计和书写繁杂的JS应用中解脱出来,将关注点转向功能需求而非实现细节上,从而提高项目的开发速度。
jQuery 是继prototype之后的又一个优秀的javascript框架。它是由 John Resig 于 2006 年初创建的,它有助于简化 JavaScript™ 以及Ajax 编程。有人使用这样的一比喻来比较prototype和jQuery:prototype就像Java,而jQuery就像ruby. 它是一个简洁快速灵活的JavaScript框架,它能让你在你的网页上简单的操作文档、处理事件、实现特效并为Web页面添加Ajax交互。

它具有如下一些特点:
1、代码简练、语义易懂、学习快速、文档丰富。
2、jQuery是一个轻量级的脚本,其代码非常小巧,最新版的JavaScript包只有20K左右。
3、jQuery支持css1-CSS3,以及基本的xPath。
4、jQuery是跨浏览器的,它支持的浏览器包括IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+。
5、可以很容易的为jQuery扩展其他功能。
6、能将JS代码和html代码完全分离,便于代码和维护和修改。
7、插件丰富,除了jQuery本身带有的一些特效外,可以通过插件实现更多功能,如表单验证、tab导航、拖放效果、表格排序、DataGrid,树形菜单、图像特效以及ajax上传等。

jQuery的设计会改变你写JavaScript代码的方式,降低你学习使用JS操作网页的复杂度,提高网页JS开发效率,无论对于js初学者还是资深专家,jQuery都将是您的首选。
jQuery适合于设计师、开发者以及那些还好者,同样适合用于商业开发,可以说jQuery适合任何JavaScript应用的地方,可用于不同的Web应用程序中。
官方站点:http://jquery.com/  中文站点:http://jquery.org.cn/

1.2、目的
通过学习本文档,能够对jQuery有一个简单的认识了解,清楚JQuery与其他JS框架的不同,掌握jQuery的常用语法、使用技巧及注意事项。

二、使用方法
在需要使用JQuery的页面中引入JQuery的js文件即可。
例如:<script type="text/javascript" src="js/jquery.js"></script>
引入之后便可在页面的任意地方使用jQuery提供的语法。

三、学习教程及参考资料
请参照《jQuery中文API手册》和http://jquery.org.cn/visual/cn/index.xml
推荐两篇不错的jquery教程:《jQuery的起点教程》和《使用 jQuery 简化 Ajax 开发》
(说明:以上文档都放在了【附件】中)

四、语法总结和注意事项

1、关于页面元素的引用
通过jquery的$()引用元素包括通过id、class、元素名以及元素的层级关系及dom或者xpath条件等方法,且返回的对象为jquery对象(集合对象),不能直接调用dom定义的方法。

2、jQuery对象与dom对象的转换
只有jquery对象才能使用jquery定义的方法。注意dom对象和jquery对象是有区别的,调用方法时要注意操作的是dom对象还是jquery对象。
普通的dom对象一般可以通过$()转换成jquery对象。
如:$(document.getElementById("msg"))则为jquery对象,可以使用jquery的方法。
由于jquery对象本身是一个集合。所以如果jquery对象要转换为dom对象则必须取出其中的某一项,一般可通过索引取出。
如:$("#msg")[0],$("div").eq(1)[0],$("div").get()[1],$("td")[5]这些都是dom对象,可以使用dom中的方法,但不能再使用Jquery的方法。
以下几种写法都是正确的:
$("#msg").html();
$("#msg")[0].innerHTML;
$("#msg").eq(0)[0].innerHTML;
$("#msg").get(0).innerHTML;

3、如何获取jQuery集合的某一项
对于获取的元素集合,获取其中的某一项(通过索引指定)可以使用eq或get(n)方法或者索引号获取,要注意,eq返回的是jquery对象,而get (n)和索引返回的是dom元素对象。对于jquery对象只能使用jquery的方法,而dom对象只能使用dom的方法,如要获取第三个< div>元素的内容。有如下两种方法:
$("div").eq(2).html();              //调用jquery对象的方法
$("div").get(2).innerHTML;       //调用dom的方法属性

4、同一函数实现set和get
Jquery中的很多方法都是如此,主要包括如下几个:
$("#msg").html();              //返回id为msg的元素节点的html内容。
$("#msg").html("<b>new content</b>");    
//将“<b>new content</b>” 作为html串写入id为msg的元素节点内容中,页面显示粗体的new content

$("#msg").text();              //返回id为msg的元素节点的文本内容。
$("#msg").text("<b>new content</b>");    
//将“<b>new content</b>” 作为普通文本串写入id为msg的元素节点内容中,页面显示粗体的<b>new content</b>

$("#msg").height();              //返回id为msg的元素的高度
$("#msg").height("300");       //将id为msg的元素的高度设为300
$("#msg").width();              //返回id为msg的元素的宽度
$("#msg").width("300");       //将id为msg的元素的宽度设为300

$("input").val(");       //返回表单输入框的value值
$("input").val("test");       //将表单输入框的value值设为test

$("#msg").click();       //触发id为msg的元素的单击事件
$("#msg").click(fn);       //为id为msg的元素单击事件添加函数
同样blur,focus,select,submit事件都可以有着两种调用方法

5、集合处理功能
对于jquery返回的集合内容无需我们自己循环遍历并对每个对象分别做处理,jquery已经为我们提供的很方便的方法进行集合的处理。
包括两种形式:
$("p").each(function(i){this.style.color=['#f00','#0f0','#00f']})    
//为索引分别为0,1,2的p元素分别设定不同的字体颜色。

$("tr").each(function(i){this.style.backgroundColor=['#ccc','#fff'][i%2]})    
//实现表格的隔行换色效果

$("p").click(function(){.html())})            
//为每个p元素增加了click事件,单击某个p元素则弹出其内容

6、扩展我们需要的功能
$.extend({
       min: function(a, b){return a < b?a:b; },
       max: function(a, b){return a > b?a:b; }
});       //为jquery扩展了min,max两个方法
使用扩展的方法(通过“$.方法名”调用):
+",min="+$.min(10,20));

7、支持方法的连写
所谓连写,即可以对一个jquery对象连续调用各种不同的方法。
例如:
$("p").click(function(){.html())})
.mouseover(function(){})
.each(function(i){this.style.color=['#f00','#0f0','#00f']});

8、操作元素的样式
主要包括以下几种方式:
$("#msg").css("background");              //返回元素的背景颜色
$("#msg").css("background","#ccc")       //设定元素背景为灰色
$("#msg").height(300); $("#msg").width("200");       //设定宽高
$("#msg").css({ color: "red", background: "blue" });//以名值对的形式设定样式
$("#msg").addClass("select");       //为元素增加名称为select的class
$("#msg").removeClass("select");       //删除元素名称为select的class
$("#msg").toggleClass("select");       //如果存在(不存在)就删除(添加)名称为select的class



JQUERY使用技巧~总结

1. 禁止右键点击
view plaincopy to clipboardprint?
1.       $(document).ready(function(){ 
2.           $(document).bind("contextmenu",function(e){ 
3.               return false; 
4.           }); 
5.       });
2. 隐藏搜索文本框文字
view plaincopy to clipboardprint?
1.       $(document).ready(function() { 
2.       $("input.text1").val("Enter your search text here"); 
3.          textFill($('input.text1')); 
4.       }); 
5.       
6.           function textFill(input){ //input focus text function 
7.           var originalvalue = input.val(); 
8.           input.focus( function(){ 
9.               if( $.trim(input.val()) == originalvalue ){ input.val(''); } 
10.       }); 
11.       input.blur( function(){ 
12.           if( $.trim(input.val()) == '' ){ input.val(originalvalue); } 
13.       }); 
14.   }
3. 在新窗口中打开链接
view plaincopy to clipboardprint?
1.       $(document).ready(function() { 
2.          //Example 1: Every link will open in a new window 
3.          $('a[href^="http://"]').attr("target", "_blank"); 
4.       
5.          //Example 2: Links with the rel="external" attribute will only open in a new window 
6.          $('a[@rel$='external']').click(function(){ 
7.             this.target = "_blank"; 
8.          }); 
9.       }); 
10.   // how to use 
11.   <A href="http://www.opensourcehunter.com" rel=external>open link</A>  4. 检测浏览器
注: 在版本jQuery 1.4中,$.support 替换掉了$.browser 变量。
view plaincopy to clipboardprint?
1.       $(document).ready(function() { 
2.       // Target Firefox 2 and above 
3.       if ($.browser.mozilla && $.browser.version >= "1.8" ){ 
4.           // do something 
5.       } 
6.       
7.       // Target Safari 
8.       if( $.browser.safari ){ 
9.           // do something 
10.   } 
11.   
12.   // Target Chrome 
13.   if( $.browser.chrome){ 
14.       // do something 
15.   } 
16.   
17.   // Target Camino 
18.   if( $.browser.camino){ 
19.       // do something 
20.   } 
21.   
22.   // Target Opera 
23.   if( $.browser.opera){ 
24.       // do something 
25.   } 
26.   
27.   // Target IE6 and below 
28.   if ($.browser.msie && $.browser.version <= 6 ){ 
29.       // do something 
30.   } 
31.   
32.   // Target anything above IE6 
33.   if ($.browser.msie && $.browser.version > 6){ 
34.       // do something 
35.   } 
36.   });  5. 预加载图片
view plaincopy to clipboardprint?
1.       $(document).ready(function() { 
2.          jQuery.preloadImages = function() 
3.         { 
4.            for(var i = 0; i").attr("src", arguments[i]);
5.         }
6.       };
7.       // how to use
8.       $.preloadImages("image1.jpg"); 
9.       });  6. 页面样式切换
view plaincopy to clipboardprint?
1.       $(document).ready(function() { 
2.           $("a.Styleswitcher").click(function() { 
3.               //swicth the LINK REL attribute with the value in A REL attribute 
4.               $('link[rel=stylesheet]').attr('href' , $(this).attr('rel')); 
5.           }); 
6.       // how to use 
7.       // place this in your header 
8.       <LINK href="default.css" type=text/css rel=stylesheet> 
9.       // the links 
10.   <A class="Styleswitcher" href="#" rel=default.css>Default Theme</A> 
11.   <A class="Styleswitcher" href="#" rel=red.css>Red Theme</A> 
12.   <A class="Styleswitcher" href="#" rel=blue.css>Blue Theme</A> 
13.   });  7. 列高度相同
如果使用了两个CSS列,使用此种方式可以是两列的高度相同。
view plaincopy to clipboardprint?
1.       $(document).ready(function() { 
2.       function equalHeight(group) { 
3.           tallest = 0; 
4.           group.each(function() { 
5.               thisHeight = $(this).height(); 
6.               if(thisHeight > tallest) { 
7.                   tallest = thisHeight; 
8.               } 
9.           }); 
10.       group.height(tallest); 
11.   } 
12.   // how to use 
13.   $(document).ready(function() { 
14.       equalHeight($(".left")); 
15.       equalHeight($(".right")); 
16.   }); 
17.   });  8. 动态控制页面字体大小
用户可以改变页面字体大小
view plaincopy to clipboardprint?
1.       $(document).ready(function() { 
2.         // Reset the font size(back to default) 
3.         var originalFontSize = $('html').css('font-size'); 
4.           $(".resetFont").click(function(){ 
5.           $('html').css('font-size', originalFontSize); 
6.         }); 
7.         // Increase the font size(bigger font0 
8.         $(".increaseFont").click(function(){ 
9.           var currentFontSize = $('html').css('font-size'); 
10.       var currentFontSizeNum = parseFloat(currentFontSize, 10); 
11.       var newFontSize = currentFontSizeNum*1.2; 
12.       $('html').css('font-size', newFontSize); 
13.       return false; 
14.     }); 
15.     // Decrease the font size(smaller font) 
16.     $(".decreaseFont").click(function(){ 
17.       var currentFontSize = $('html').css('font-size'); 
18.       var currentFontSizeNum = parseFloat(currentFontSize, 10); 
19.       var newFontSize = currentFontSizeNum*0.8; 
20.       $('html').css('font-size', newFontSize); 
21.       return false; 
22.     }); 
23.   });  9. 返回页面顶部功能
view plaincopy to clipboardprint?
1.       $(document).ready(function() { 
2.       $('a[href*=#]').click(function() { 
3.        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') 
4.        && location.hostname == this.hostname) { 
5.          var $target = $(this.hash); 
6.          $target = $target.length && $target 
7.          || $('[name=' + this.hash.slice(1) +']'); 
8.          if ($target.length) { 
9.         var targetOffset = $target.offset().top; 
10.     $('html,body') 
11.     .animate({scrollTop: targetOffset}, 900); 
12.       return false; 
13.      } 
14.     } 
15.     }); 
16.   // how to use 
17.   // place this where you want to scroll to 
18.   <A name=top></A> 
19.   // the link 
20.   <A href="#top">go to top</A> 
21.   });  11.获得鼠标指针XY值
view plaincopy to clipboardprint?
1.       $(document).ready(function() { 
2.          $().mousemove(function(e){ 
3.            //display the x and y axis values inside the div with the id XY 
4.           $('#XY').html("X Axis : " + e.pageX + " | Y Axis " + e.pageY); 
5.         }); 
6.       // how to use 
7.       <DIV id=XY></DIV> 
8.       
9.       });  12. 验证元素是否为空
view plaincopy to clipboardprint?
1.       $(document).ready(function() { 
2.         if ($('#id').html()) { 
3.          // do something 
4.          } 
5.       });  13. 替换元素
view plaincopy to clipboardprint?
1.       $(document).ready(function() { 
2.          $('#id').replaceWith('
3.       <DIV>I have been replaced</DIV>
4.      
5.       '); 
6.       });
14. jQuery延时加载功能
view plaincopy to clipboardprint?
1.       $(document).ready(function() { 
2.          window.setTimeout(function() { 
3.            // do something 
4.          }, 1000); 
5.       });
15. 移除单词功能
view plaincopy to clipboardprint?
1.       $(document).ready(function() { 
2.          var el = $('#id'); 
3.          el.html(el.html().replace(/word/ig, "")); 
4.       });
16. 验证元素是否存在于Jquery对象集合中
view plaincopy to clipboardprint?
1.       $(document).ready(function() { 
2.          if ($('#id').length) { 
3.         // do something 
4.         } 
5.       });
17. 使整个DIV可点击
view plaincopy to clipboardprint?
1.       $(document).ready(function() { 
2.           $("div").click(function(){ 
3.             //get the url from href attribute and launch the url 
4.             window.location=$(this).find("a").attr("href"); return false; 
5.           }); 
6.       // how to use 
7.       <DIV><A href="index.html">home</A></DIV> 
8.       
9.       });
18.ID与Class之间转换
当改变Window大小时,在ID与Class之间切换
view plaincopy to clipboardprint?
1.       $(document).ready(function() { 
2.          function checkWindowSize() { 
3.           if ( $(window).width() > 1200 ) { 
4.               $('body').addClass('large'); 
5.           } 
6.           else { 
7.               $('body').removeClass('large'); 
8.           } 
9.          } 
10.   $(window).resize(checkWindowSize); 
11.   });
19. 克隆对象
view plaincopy to clipboardprint?
1.       $(document).ready(function() { 
2.          var cloned = $('#id').clone(); 
3.       // how to use 
4.       <DIV id=id></DIV> 
5.       
6.       });
20. 使元素居屏幕中间位置
view plaincopy to clipboardprint?
1.       $(document).ready(function() { 
2.         jQuery.fn.center = function () { 
3.             this.css("position","absolute"); 
4.             this.css("top", ( $(window).height() - this.height() ) / 2+$(window).scrollTop() + "px"); 
5.             this.css("left", ( $(window).width() - this.width() ) / 2+$(window).scrollLeft() + "px"); 
6.             return this; 
7.         } 
8.         $("#id").center(); 
9.       });
21. 写自己的选择器
view plaincopy to clipboardprint?
1.       $(document).ready(function() { 
2.          $.extend($.expr[':'], { 
3.              moreThen1000px: function(a) { 
4.                  return $(a).width() > 1000; 
5.             } 
6.          }); 
7.         $('.box:moreThen1000px').click(function() { 
8.             // creating a simple js alert box 
9.             alert('The element that you have clicked is over 1000 pixels wide'); 
10.     }); 
11.   });
22. 统计元素个数
view plaincopy to clipboardprint?
1.       $(document).ready(function() { 
2.          $("p").size(); 
3.       });
23. 使用自己的 Bullets
view plaincopy to clipboardprint?
1.       $(document).ready(function() { 
2.          $("ul").addClass("Replaced"); 
3.          $("ul > li").prepend("? "); 
4.        // how to use 
5.        ul.Replaced { list-style : none; } 
6.       });
24. 引用Google主机上的Jquery类库
Let Google host the jQuery script for you. This can be done in 2 ways.
view plaincopy to clipboardprint?
1.       //Example 1 
2.       <SCRIPT src="http://www.google.com/jsapi"></SCRIPT> 
3.       <SCRIPT type=text/javascript>
4.       google.load("jquery", "1.2.6");
5.       google.setOnLoadCallback(function() {
6.           // do something
7.       });
8.       </SCRIPT><SCRIPT src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type=text/javascript></SCRIPT> 
9.       
10.    // Example 2:(the best and fastest way) 
11.   <SCRIPT src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type=text/javascript></SCRIPT>

25. 禁用Jquery(动画)效果
view plaincopy to clipboardprint?
1.       $(document).ready(function() { 
2.           jQuery.fx.off = true; 
3.       });
26. 与其他Javascript类库冲突解决方案
view plaincopy to clipboardprint?
1.       $(document).ready(function() { 
2.          var $jq = jQuery.noConflict(); 
3.          $jq('#id').show(); 
4.       });





jquery 使用的一些总结 收藏
jQuery 对象转成DOM 对象:

var dom=jqueryObj.get(0);

或var domObj=jqueryObj[0];

DOM 对象转成jQuery 对象:

对于已经是一个DOM 对象,只需要用$()把DOM 对象包装起来,就可以获得一个jQuery 对象了。$(DOM 对象)

var jqueryObj=$(domObj); 

一个片段

$( function() {

    var t = $("#t");
    var show = $("#showArea");

//用ajax 从服务器端传回的xml 格式的数据
    $.get("AJAXServer", null, function(resp) {

        var tab = resp.getElementsByTagName("table")[0];

        var t2 = tab.cloneElement();
        // show.append($(t2)); //将dom 对像转换为jquery 对象后加入document
            show.get(0).appendChild(t2); // 将jquery 对象转换成dom 对象后
        }, "xml"

    )

}

)

============================================================

//str 为xml 格式的字符串,开头可以有<?xml version="1.0" encoding="UTF-8"?>的声明 ,也可以没有F
function createXMLDOM(str) {
    var oXmlDom;
    var arrSignatures = [ "MSXML2.DOMDocument.6.0", "MSXML2.DOMDocument.5.0",
            "MSXML2.DOMDocument.4.0", "MSXML2.DOMDocument.3.0",
            "MSXML2.DOMDocument", "MSXML.DOMDocument", "Microsoft.XmlDom" ];
    if (window.ActiveXObject) {
        for ( var i = 0; i < arrSignatures.length; i++) {
            try {
                var oXmlDom = new ActiveXObject(arrSignatures[i]);
                oXmlDom.loadXML(str);
                // return oXmlDom;
                break;
            } catch (oError) {
                // ignore
            }
        }
    } else {
        try {
            var Parser = new DOMParser();
            oXmlDom = Parser.parseFromString(str, "text/xml");
        } catch (e) {
        }
    }

    if (oXmlDom == null) {
        // throw new Error("MSXML没有安装");
    }

    return oXmlDom;
}

// clone attributes,and the node self ,no child is cloned
// 进行dom Element节点 的浅层复制
function cloneSimpleEle(root) {
    if (root.nodeType == 1) {
        var root_clone_ = document.createElement(root.tagName);
        if (root.attributes && root.attributes.length > 0) {
            var attr_len = root.attributes.length;
            for ( var j = 0; j < attr_len; j++) {
                var attr = root.attributes[j];
                root_clone_.setAttribute(attr.nodeName, attr.nodeValue);
            }
        }
        return root_clone_;

    }

}
/*
* 此函数,用于DOM Element 的复制,返回一个几乎与参数一致的Dom Element
* (有一些差别,如忽略了注释等无关紧要的东西,只复制了其中的文本节点和标签,) 另外,传进去的参数不仅可以是html中的DOM 对象,也可以是xml
* 中的DOM 对像, 如果您想用此函数进行html 中dom 节点的复制,建议用 系统自带的函数dom.cloneNode(deep_boolean);
* 进行深层或浅层的复制,此函数存在 的理由,主要是适用于xml dom对像向html dom对像转化的情形, 例如处理ajax
* 返回的xml数据,(直接返回的dom对像没法在html 的document 中进行appendChild() ,insertBefore()
* 等操作,经过此函数处理之后的对像则可以)

*用法 var div=document.getElementById("id1");

var div_clone=cloneElement(div);

有了下面这个函数,则可以简化为

var div_clone=div.cloneElement();

Element.prototype.cloneElement = function() {

*/
function cloneElement(root) {
    var root_clone = cloneSimpleEle(root);

    if (root.hasChildNodes()) {
        var child_len = root.childNodes.length;
        for ( var i = 0; i < child_len; i++) {
            var child = root.childNodes[i];
            var clone;
            if (child.nodeType == 3) {
                clone = document.createTextNode(child.nodeValue);
            } else if (child.nodeType == 1) {
                clone = cloneElement(child);
            }
            root_clone.appendChild(clone);
        }
    }
    return root_clone;
}
Element.prototype.cloneElement = function() {
    var root_clone = cloneSimpleEle(this);

    if (this.hasChildNodes()) {
        var child_len = this.childNodes.length;
        for ( var i = 0; i < child_len; i++) {
            var child = this.childNodes[i];
            var clone;
            if (child.nodeType == 3) {
                clone = document.createTextNode(child.nodeValue);
            } else if (child.nodeType == 1) {
                clone = cloneElement(child);
            }
            root_clone.appendChild(clone);
        }
    }
    return root_clone;

}

// ============================= start of js lib for
// ajax==============================================================================================================================
var http_request = false;
var callback_func;

// 使用说明
// 二,在页面使用如下代码将js文件包含进来:
// <script language=javascript src="ajax.js"></script>

// 三,在页面调用sendRequest(...)方法:
// 如:<a href="javascript:sendRequest(param,function,'GET')" >调用AJAX</a>
// 或:<input type="button" value="提交"
// onclick="sendRequest('post.do',param,function,'POST')" />
// 注释(以第一个为例):
// 暂时就不用了 default.do: 这个例子采用ajax通过一个链接请求default.do页面,
// param:
// 为参数,可以为空,也可以不为空,比如name=value&password=123456,也可以通过把一个表单(form)的字段组合起来作为一个字符串传递
// 过去,
// function: 是你自己写的一个函数,用于处理返回的内容,一般的处理是
// 将返回的内容显示在页面,一个典型的例子:
// function search(str){
// alert(str); //用于调试.
// myId.innerHTML = str;
// }
// GET: 是请求的方法,简单的说,get代表请求一个资源,post代表提交参数并请求资源.
// 发送ajax请求 get或post 完全兼容 IE FireFox各个版本,程序在 IE5.0,6.0,7.0,8.0
// FireeFox2.0,30下均做了全面测试
function sendRequest(url, argstr, func, method) {

    http_request = false;
    callback_func = func;

    if (window.XMLHttpRequest) { // Mozilla, Safari,...
        http_request = new XMLHttpRequest();
        // if (http_request.overrideMimeType) {
        // http_request.overrideMimeType('text/xml');
        // }
    } else if (window.ActiveXObject) { // IE
        try {
            http_request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
            }
        }
    }

    if (!http_request) {
        alert('不能建立 XMLHTTP 对象');
        return false;
    }

    if (method == 'GET') {
        // http_request.onreadystatechange = alertContents;
        http_request.open('GET', url + '?' + argstr, false); // 目前是同步 true:异步
                                                                // false:同步
        http_request.send(null);
        alertContents();
    } else {
        // http_request.onreadystatechange = alertContents;
        http_request.open('POST', url + '', false);
        http_request.setRequestHeader("Content-Type",
                "application/x-www-form-urlencoded; charset=utf-8");

        http_request.send(argstr);
        alertContents();
    }
}

// 延迟处理,超时后的处理
function alertContents() {
    if (http_request.readyState == 4) {
        if (http_request.status == 200 || http_request.status == 0) {
            callback_func(http_request.responseText);
        } else {
            alert('服务端返回状态: ' + http_request.statusText);
        }
    } else {
        // alert('数据加载中...');
    }
}
// =====================================end of
// ajax========================================================================





//==========================================================================================

//取出url中的各个参数对应的值 url参数解析
//如 果url 中并无strParamName ,则返回空字符中“”

// 如:getURLParam("name", "http://writeblog.csdn.net/PostEdit.aspx?name=111") 返回111 或无则空串
function getURLParam(strParamName, url) {
  var strReturn = "";
  var strHref = url.toLowerCase();
  if (strHref.indexOf("?") > -1) {
      var strQueryString = strHref.substr(strHref.indexOf("?") + 1).toLowerCase();
      var aQueryString = strQueryString.split("&");
      for (var iParam = 0; iParam < aQueryString.length; iParam++) {
          if (aQueryString[iParam].indexOf(strParamName.toLowerCase() + "=") > -1) {
              var aParam = aQueryString[iParam].split("=");
              strReturn = aParam[1];
              break;
          }
      }
  }
  return strReturn;
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics