GoAhead4.1.0 开发总结三(GoAction+Ajax实现局部数据交互)

环境

官方文档:https://www.embedthis.com/goahead/doc/

源码下载: goahead-4.1.0-src.tgz

系统平台:Ubuntu 12.04.4

gcc version 4.6.3

ajax

“Asynchronous JavaScript and XML”(异步JavaScript和XML)

我们操作网页时往往只需要刷新网页上的一部分数据甚至可能是一个文本框内的数据,但是采用传统的刷新方式服务器会把整个页面重新发送至浏览器,浏览器再加载整个页面,这样不仅浪费了带宽,而且整个页面刷新视觉上也不流畅。

ajax技术解决了这一问题,ajax的思路是我需要刷新局部数据时给服务器一个请求,服务器收到请求后将数据将需要刷新的数据回送,浏览器接受到数据后通过脚本更新相应位置的数据,这个过程必须是在后台进行的。实现这个过程的核心便是JavaScript对象XmlHttpRequest。该对象在是一种支持异步请求的技术。简而言之,XmlHttpRequest使您可以使用JavaScript向服务器提出请求并处理响应,而不阻塞用户。

ajax局部刷新实现

1.前端页面添加 ajax 支持,并调用指定的 goaction 函数

<!DOCTYPE html>
<html>
<head>
    <title>test.html</title>
    <meta charset="UTF-8">
</head>
<body>
    <p>Please log in</p>
    <form action=/action/test method="post">
        <table>
        <tr><td>账号:</td><td><input type="text" name="name"></td></tr>
        <tr><td>密码:</td><td><input type="password" name="address"></td></tr>
        <tr><td><input type="submit" name="submit" value="submit"></td>
            <td><input type="reset" value="reset"></td></tr>
        </table>
    </form>
    
    <script type="text/javascript">
    function loadXMLDoc()
    {
        var xmlhttp;
        if (window.XMLHttpRequest)
          {// code for IE7+, Firefox, Chrome, Opera, Safari
              xmlhttp=new XMLHttpRequest();
          }
        else
          {// code for IE6, IE5
              xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
          }
        xmlhttp.onreadystatechange=function()
          {
              if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
                document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
                }
          }
        xmlhttp.open("GET","action/test",true);
        xmlhttp.send();
    }
    </script>
    
    <div id="myDiv"><h2>需要刷新的局部内容</h2></div>
    <button type="button" onclick="loadXMLDoc()">通过 AJAX 实现局部刷新</button>
    
</body>
</html>

document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

用回复的http文本 替换 id="myDiv" 节的内容

xmlhttp.open("GET","action/test",true);

xmlhttp.send();

向指定URL发送请求,goahead中将 goaction过程的后端C函数绑定到了具体的URL链接;

这样向"action/test"发送GET请求,即会执行定义的 actionTest 函数,然后 ajax 语法就实现部分页面的刷新;

 

2.后台 定义 “test” action函数

// Main 中添加 goAction定义
websDefineAction("test", actionTest);    // goAction定义

static void actionTest(Webs *wp)
{
    cchar    *name, *address;

    name = websGetVar(wp, "name", NULL);
    address = websGetVar(wp, "address", NULL);
    websSetStatus(wp, 200);
    websWriteHeaders(wp, -1, 0);
    websWriteEndHeaders(wp);
    websWrite(wp, "<html><body><h2>name: %s, address: %s</h2></body></html>\n", name, address);
    websFlush(wp, 0);
    websDone(wp);
}

3.编译并测试

运行 ./m283-webs -v ./web/

在浏览器输入 http://192.168.1.124/test.html

点击 刷新 按钮

这样就实现了页面的局部刷新

至此测试完成了 前后台控制和数据交互、页面局部刷新功能。

 

posted @ 2019-06-06 10:08  silencehuan  阅读(3165)  评论(0编辑  收藏  举报