1.前言
最近有个需求要实现我原来写的pc版本软件移植成网络版,而网站是用php架设的,故需要用到在html中使用php返回的数据进行界面更新,原来没接触过这块,边学边搞,一个星期左右实现了一个简单的登录,注册,配置的网页版本
2.思路
html通过js发送http请求,php返回加工过的数据,js通过回调函数加载数据。以下是用户申请防护ip后,加载到table中的例子
3.代码片段
1.html+js部分
//js代码
<script type="text/javascript">
var xmlHttp;
function createXMLHttpRequest(){
if(window.ActiveXObject){
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
}
function start(){
createXMLHttpRequest();
var url="http://www.52300.com/yzydede/yhsetipmap.php";
xmlHttp.open("POST",url,true);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttp.onreadystatechange = callback;
xmlHttp.send("sip="+document.getElementById("sip").value);
}
function callback(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200 && xmlHttp.responseText != ""){
if (xmlHttp.responseText.indexOf("127") >= 0)
{
var bodyObj=document.getElementById("ipmap_list");
if(bodyObj==null)
{
alert("Body of Table not Exist!");
return;
}
var rowCount = bodyObj.rows.length;
var cellCount = bodyObj.rows[0].cells.length;
var newRow = bodyObj.insertRow(rowCount++);
newRow.insertCell(0).innerHTML=rowCount - 1;
newRow.insertCell(1).innerHTML=document.getElementById("sip").value;
newRow.insertCell(2).innerHTML=xmlHttp.responseText;
}
else
alert(xmlHttp.responseText);
}
}
}
function getyhip(){
createXMLHttpRequest();
var url="http://www.52300.com/yzydede/yhgetipmap.php";
xmlHttp.open("POST",url,true);
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttp.onreadystatechange = yhcallback;
xmlHttp.send("");
}
function yhcallback(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200 && xmlHttp.responseText != ""){
if (xmlHttp.responseText.indexOf(".") >= 0)
{
var bodyObj=document.getElementById("ipmap_list");
if(bodyObj==null)
{
alert("Body of Table not Exist!");
return;
}
var strall= new Array();
strall=xmlHttp.responseText.split("|");
for (i=0; i<strall.length ;i++ )
{
var allip = new Array();
allip = strall[i].split("-");
var rowCount = bodyObj.rows.length;
var cellCount = bodyObj.rows[0].cells.length;
var newRow = bodyObj.insertRow(rowCount++);
newRow.insertCell(0).innerHTML=rowCount - 1;
for (j=0; j<allip.length; j++)
newRow.insertCell(1+j).innerHTML=allip[j];
}
}
else
alert(xmlHttp.responseText);
}
}
}
</script>
//点击按钮触发更新
<input style="width:150px;margin-top:10px; margin-bottom:20px;" class="button_blue" type="button" value="申请防护" onclick="start()" />
//刷新网页更新
<script type="text/javascript">
getyhip();
</script>
2.php代码
<?php
echo "hello world.";
?>
4.备注