欢迎光临
我们一直在努力

用Go语言进行ajax回传

参考:https://studygolang.com/articles/2671

main.go内容

package main

import (
	"io"
	"net/http"
	"text/template"
)

func OnAjax(res http.ResponseWriter, req *http.Request) {
	io.WriteString(res, "这是从后台发送的数据")
}

func index(w http.ResponseWriter, r *http.Request) {
	t, _ := template.ParseFiles("index.html") //找模板
	t.Execute(w, nil)                         //执行模板
}

func main() {
	http.Handle("/js/", http.StripPrefix("/js/", http.FileServer(http.Dir("js"))))

	http.HandleFunc("/", index)      //函数也是一种变量
	http.HandleFunc("/ajax", OnAjax) //函数也是一种变量
	http.ListenAndServe("localhost:8081", nil)
}

index.html

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>Go语言与ajax示例</title>

    <script type="text/javascript" src="js/loli.js"></script>
</head>
<body>
    <p><input id="btn1" type="button" value="按钮" /></p>
    <p><input id="txt1" type="text" /></p>
</body>
</html>

js文件

window.onload = main;

function main() {
    var oBtn = document.getElementById('btn1');
    oBtn.onclick = OnButton1;
}

function OnButton1() {
    var xhr = new XMLHttpRequest();
    xhr.open('get', '/ajax', true);
    xhr.send();

    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4) { // 读取完成
            if (xhr.status == 200) {
                var oTxt = document.getElementById('txt1');
                oTxt.value = xhr.responseText;
            }
        }
    }
}
 收藏 (0) 打赏

您可以选择一种方式赞助本站

支付宝扫一扫赞助

微信钱包扫描赞助

未经允许不得转载:家里蹲的狐狸 » 用Go语言进行ajax回传

分享到: 生成海报
avatar

热门文章

  • 评论 抢沙发

    • QQ号
    • 昵称 (必填)
    • 邮箱 (必填)
    • 网址

    登录

    忘记密码 ?

    切换登录

    注册

    我们将发送一封验证邮件至你的邮箱, 请正确填写以完成账号注册和激活