Blogger Information
Blog 33
fans 0
comment 2
visits 41990
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
原生JS如何无刷新Post表单数据
hanyufeng的博客
Original
1031 people have browsed it

无刷新提交表单数据可使用Ajax对象,例如:

//生成Ajax对象
var xhr = new XMLHttpRequest();
//事件监听
xhr.onreadystatechange = function () {
    if(xhr.readyState == 4 && xhr.status == 200){
            //处理返回数据
            }
}

xhr.open('post', 'check.php', true);

//设置头信息,将内容类型设置为表单提交方式
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

//post表单数据
var data =  ……  //构造参数
xhr.send(data);

注意构造参数不能写:

var data = serialize(document.forms[0])

浏览器会报错:

Uncaught ReferenceError: serialize is not defined

serialize 并不是JavaScript本身的函数,是JQuery的函数,不能在这里使用。

原生JS需要连接字符来构造参数,例如:

var userName = ……  
var passWord = …… 
var data = 'username='+ userName + '&password=' + passWord ;
xhr.send(data);

或者使用FormData表单对象:

var formdata = new FormData(document.forms[0]);


注:

如果将上述第一部分代码(试图使用serialize函数)绑定在 button 元素的onclick事件,并且button 的类型未指定或为submit,如:

<button>提交</button> //不设置类型,即默认为submit 类型
<button type="submit">提交</button>

那么第一部分的代码不会报错,可以提交,但页面会刷新。

这是因为button 按钮用传统方式提交了表单。

Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!