go ajax接口,go ajax

本文介绍了如何在Go语言的web应用中使用AJAX技术实现前后端数据交互,并展示了HTML模板在渲染页面中的应用。通过实例展示,读者将理解如何在`main.go`中设置静态资源路径,以及在`index.html`中利用JS调用后端API `/onAjax`。
摘要由CSDN通过智能技术生成

1. 目录结构

|-- main.go

|-- template

|--index.html

|--public

|-- js

|-- js.js

共有三个文件main.go ,index.html和js.js。 template和public/js都为目录。

2. main.go

package main

import (

"fmt"

"html/template"

"io"

"net/http"

)

func main() {

mux := http.NewServeMux()

files := http.FileServer(http.Dir("./public"))

mux.Handle("/static/", http.StripPrefix("/static/", files))

mux.HandleFunc("/", index)

mux.HandleFunc("/onAjax", onAjax)

server := &http.Server{

Addr:    "0.0.0.0:8080",

Handler: mux,

}

server.ListenAndServe()

fmt.Println("it is finished")

}

func index(w http.ResponseWriter, r *http.Request) {

fmt.Println("in Index")

t, err := template.ParseFiles("template/index.html")

if err != nil {

fmt.Println(err)

return

}

err = t.Execute(w, nil)

}

func onAjax(w http.ResponseWriter, r *http.Request) {

fmt.Println("in onAjax")

io.WriteString(w, "this is from home")

}

3 js.js

//window.onload = main;

//function main(){

//var oBtn = document.getElementById("butn1");

//oBtn.οnclick=loadXMLDoc();

//}

function loadXMLDoc()

{

var xmlhttp;

xmlhttp= new XMLHttpRequest();

xmlhttp.onreadystatechange=function()

{

if(xmlhttp.readyState==4 && xmlhttp.status == 200)

{

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

}

}

xmlhttp.open("GET","/onAjax",true);

xmlhttp.send();

}

4 index.html

use ajax 2

change data

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值