English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Example of beego getting AJAX data

1. What is AJAX

Asynchronous JavaScript And XML (AJAX) refers to a web development technology for creating interactive web applications

Ajax is a technology that can update part of the web page without reloading the entire web page.

2. How to use AJAX

XMLHttpRequest is the foundation of AJAX.

XMLHttpRequest is used to exchange data with the server in the background. This means that a part of the web page can be updated without reloading the entire web page.

Using AJAX is roughly divided into four steps

1. Create an XMLHttpRequest object

//js code to obtain the XMLHttpRequest object (saved as util.js)
function getXmlHttpRequest() {
  var xhr;
  try {
    // Firefox, Opera 8.0+, Safari
    xhr = new XMLHttpRequest();
  } catch (e) {
    // Internet Explorer
    try {
      xhr = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
      try {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (e) {
        alert("Your browser does not support AJAX!");
        return false;
      }
    }
  }
  return xhr;
}

2. Register the status callback function (this callback function is called each time the readyState of the XMLHttpRequest object changes)

//when xhr.readyState == 4all steps have been completed
//when xhr.state == 200 indicates that it has been executed correctly
 xhr.onreadystatechange=function(){
  if(xhr.readyState == 4 && xhr.state == 200){
    alert("All requests have been executed and were successful");
  }
}

3. Establish an asynchronous connection with the server (asynchronous by default)

/**
 open(method,url,async) method
 Specify the type of request, URL, and whether the request is handled asynchronously.
 method: The type of request; GET or POST
 url: The URL for the request to be processed
 async: true (asynchronous) or false (synchronous)
 Ensure that each new request is sent by time
*/
xhr.open("Post", "/detailsU?time=" + new Date().getTime());

4. Make an asynchronous request

/**
 send method sends a JSON formatted string
*/
xhr.send('{"Index":"'+index +'", "Change":"' + i +'"}');

By following these four steps, you can successfully send the request

Source code attached:

{{range .PhoneDetails}}  
    <tr onclick="func1(this)">
      <th>{{.Id}}</th>
      <th>{{.Name}}</th>
      <th>{{.Price}}</th>
      <th>{{.Repertory}}</th>
      <th>
        <a href="">Edit
      </th>
      <script type="text/javascript" src="/static/js/util.js"></script>
      <script type="text/javascript">
        function func1(x) {
          var code = prompt("Please enter the adjusted stock size:");
          if(code != null && code != "") {
            var i = parseInt(code);
            if(isNaN(i)) {
              alert('Input error');
            } else {
              var xhr = getXmlHttpRequest();
              xhr.onreadystatechange = function() {
                if(xhr.readyState == 4 && xhr.state == 200) {
                  alert("All requests have been executed and were successful");
                }
              }
              var index = x.rowIndex;
              xhr.open("Post", "/detailsU?time=" + new Date().getTime());
              xhr.send('{"Index":"' + index + '", "Change":"' + i + '"}');
              alert('Update successful');
            }
          } else {
            alert('Input error');
          }
        }
      </script>
    </tr>
    {{end}}

3. Handle AJAX requests in beego

1. First create the data structure in the models layer's models.go

/**
 corresponds to the incoming JSON format string
 '{"Index":"'+index +'", "Change":"' + i +'"}
*/
type Object struct {
 Index string
 Change string
}

2. Register the corresponding routes

/**
 Register the corresponding routes in main.go (note that they are set up with the corresponding routes)
 xhr.open("Post", "/detailsU?time=" + new Date().getTime());
 "Post:DoUpdate" is used to register the function that handles the Post method request for this URL
*/
beego.Router("/detailsU", &controllers.DetailController{}, "Post:DoUpdate")

3. Write the corresponding handling function in the controller

/**
 Process the corresponding requests in the corresponding function
 json.Unmarshal(this.Ctx.Input.RequestBody, ob)
 Parse the incoming data through json and store the data in the ob object
 Set copyrequestbody = true in app.conf
*/
func (this *DetailController) DoUpdate(){
    ob := &models.Object{}
    json.Unmarshal(this.Ctx.Input.RequestBody, ob)
    db, err := sql.Open("mysql", "Username:Password@tcp(IP:3306)/Database Name)
    result, err := db.Exec("UPDATE 数据表名 SET 字段= ? WHERE id = ?",ob.Change, ob.Index);
    if err != nil{
      beego.Error(err)
      return
    }
       fmt.Println(result)
    }
}

This example of getting AJAX data with beego is all the editor shares with everyone. Hope it can give you a reference, and also hope everyone will support the呐喊 tutorial more.

Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal responsibility. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report violations, and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)

You May Also Like