Chinaunix首页 | 论坛 | 博客
  • 博客访问: 2534333
  • 博文数量: 245
  • 博客积分: 4125
  • 博客等级: 上校
  • 技术积分: 3113
  • 用 户 组: 普通用户
  • 注册时间: 2009-03-25 23:56
文章分类

全部博文(245)

文章存档

2015年(2)

2014年(26)

2013年(41)

2012年(40)

2011年(134)

2010年(2)

分类: 系统运维

2010-12-04 00:35:48


PHP+AJAX+POST DEMO[code]
以POST方式传值时,在服务端back.php接受数据时需要设置
xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
否则,接收不到数据。另外还要注意一些编码的问题。
 
该demo由3个文件组成,前端index.html,ajax.js,服务端back.php
 
以下是完整代码:
index.html
 
 


<html>
<head>
  <title>ajax post php</title>
  <script src="ajax.js" type="text/javascript"></script>
</head>
<body>
 <div style="color:red"; id="result">
 here the content..
 </div>

 <form name="form1" id="form1" method="post" action="" onsubmit="send();return false;">

  姓名:<input type="text" name="name" value="Linus"/><br/>
  标题:<input type="text" name="title" value="Title "/><br/>
  内容:<input type="text" name="content" value="Contentsssss"/><br/>

  <input type="submit" name="postit" value="Do it"/>
 </form>
 </body>
</html>

 
ajax.js
 
 

//ajax.js

 function send(){

            // instantiate XMLHttpRequest object

            try
            {
                xhr = new XMLHttpRequest();
            }
            catch (e)
            {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }

            // handle old browsers

            if (xhr == null)
            {
                alert("Ajax not supported by your browser!");
                return;
            }

            //construct data

            var name = document.form1.name.value;
            var title = document.form1.title.value;
            var content = document.form1.content.value;
            var sendData = "name="+escape(name)+"&title="+escape(title)+"&content="+escape(content);
            //sendData = encodeURI(sendData);

            //alert(sendData);

            var url = "back.php";


            xhr.onreadystatechange = handle;

            xhr.open("post",url,true);
            //xhr.setrequestheader("content-length",sendData.length);

            xhr.setRequestHeader("cache-control","no-cache");
            //without the line the back.php can not receive post data

            xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
            xhr.send(sendData);


  }


 function handle(){
      // only handle loaded requests

     if(xhr.readyState ==4){
        if(xhr.status == 200){
           document.getElementById('result').innerHTML = xhr.responseText;
        }else{
           alert("error occured");
        }

     }

 }


back.php
 
 

<?php

 echo $_POST['name']." ---".$_POST['title']."---".$_POST['content']."
"
;
 //sleep(2);

?>


阅读(1877) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~