Example of jQuery + koa2 implementing a simple Ajax request, jquerykoa2

Source: Internet
Author: User

Example of jQuery + koa2 implementing a simple Ajax request, jquerykoa2

Preface

Previously, I wrote Ajax Code only for front-end implementation. I felt that my understanding of Ajax requests was not deep enough. Therefore, I wrote this small Ajax implementation demo from the front-end to the back-end to achieve simple implementation.GETAndPOSTRequests to enhance the understanding of front-end interaction.

Technology Stack

  1. Koa2
  2. JQuer

Requirement

Some logics can be processed directly at the front end. The logic is sent to the backend for better understanding.AjaxRequest.

POST

Enter the number and name, and send a POST request to save the personnel information. If the information is not filled in or is incorrect, a format error reminder is provided; if the information is filled in correctly but the number already exists, a reminder is given. If the information is filled in correctly and the number does not exist, the message is saved successfully.

GET

Enter the serial number and send a GET request to query the personnel information. If the serial number is not filled in or is incorrectly filled in, an error message is displayed. If the serial number is correct and the serial number already exists, the system returns the personnel information; if the information is correct but the number does not exist, an error message indicating that the person does not exist is displayed.

File List

  1. Dist
    1. Index.html
    2. Index. js
  2. Server. js
  3. Router. js

Front-end implementation

Html page

index.html, Simple html page, sent by clicking the buttonjsonFormatAjaxRequest:

<! DOCTYPE html> 

JQuery sends Ajax requests

SendGETRequest:

var searchButton = $('#search');var personNumber = $('#person-number').val();searchButton.click(() => { var number = $('#search-number').val(); $.ajax({  type: 'GET',  url: `person/?number=${number}` })});

SendPOSTRequest:

var saveButton = $('#save').click(() => { var number = $('#person-number').val(); var name = $('#person-name').val(); $.ajax({  type: 'POST',  url: 'person',  dataType: 'json',  data: {   number: number,   name: name  } })});

Process returned json data

PassajaxCompleteData returned by event processing. This event can only be bounddocumentObject:

// Ajax completion event $ (document ). ajaxComplete (function (event, xhr, settings) {var obj = JSON. parse (xhr. responseText); var data = obj. data; if (obj. success & data ['number']) {$ ('# message '). text ('name: $ {data ['name']} No.: $ {data ['number']} ');} else {$ (' # message '). text (data );}});

Backend implementation

Web Server

Passkoa2To implement a simple Web server.server.js:

Const path = require ('path'); const serve = require ('koa-static '); const koa = require ('koa '); const koaBody = require ('koa-body'); // parse the Request body in multipart, urlencoded, and json format const router = require ('. /router. js'); const app = new Koa (); app. use (serve (path. join (_ dirname ,'. /dist '); // read the static front-end page app. use (koaBody (); // you can use this middleware to parse the request body of the post request to obtain the data app. use (router. routes (); app. listen (3000); console. log ('listening on port 3000 ');

Process requests through routing

ProcessingGETRequest, andjsonReturns data in the string format. PassGETThe query parameters sent by the request are stored inctx.queryAttribute:

Router. get ('/person', (ctx, next) => {let number = ctx. query. number; let temp = {}; // determine whether the serial number contains temp. data =/^ [0-9] + $ /. test (number )? (People [number]? People [number]: 'Number does not exist'): 'Number format error '; temp. success = !! Temp. data ['number']; ctx. body = JSON. stringify (temp); // responds to the request and sends the processed information to the client });

ProcessingPOSTRequest, andjsonReturns data in the string format. The data in the POST request is stored in the Request body.koa-bodyMiddleware can passctx.request.bodyGET request data:

Router. post ('/person', (ctx, next) => {let query = ctx. request. body; let temp ={}; // The number must be a number greater than 0, and the name must exist if (/^ [0-9] + $ /. test (query. number) & query. name & parseInt (query. number, 10)> 0) {// determine whether the number exists if (! People [query. number]) {// Save the information people [query. number] = {number: parseInt (query. number, 10), name: query. name}; temp. success = true; temp. data = 'saved successfully';} else {temp. success = false; temp. data = 'No. already exists';} else {temp. success = false; temp. data = 'message format error';} ctx. body = JSON. stringify (temp );});

Completerouter.js:

Const Router = require ('koa-router '); const router = new Router (); // The initial personnel information object, where the information is stored and read. Const people = {1: {number: 1, name: 'Dan friedel'}, 2: {number: 2, name: 'Anna matteo'}, 3: {number: 3, name: 'Susan shand'}, 4: {number: 4, name: 'bryan Lynn '}, 5: {number: 5, name: 'mario Ritter '},}; router. get ('/person', (ctx, next) => {let number = ctx. query. number; let temp = {}; // the object to be returned to the client. The success attribute is used to determine whether the access is successful. // Determine whether the serial number contains temp. data =/^ [0-9] + $/. test (number )? (People [number]? People [number]: 'Number does not exist'): 'Number format error '; temp. success = !! Temp. data ['number']; ctx. body = JSON. stringify (temp) ;}); router. post ('/person', (ctx, next) => {let query = ctx. request. body; let temp ={}; // The number must be a number greater than 0, and the name must exist if (/^ [0-9] + $ /. test (query. number) & query. name & parseInt (query. number, 10)> 0) {// determine whether the number exists if (! People [query. number]) {// Save the information people [query. number] = {number: parseInt (query. number, 10), name: query. name}; temp. success = true; temp. data = 'saved successfully';} else {temp. success = false; temp. data = 'No. already exists';} else {temp. success = false; temp. data = 'message format error';} ctx. body = JSON. stringify (temp) ;}); module. exports = router;

Test

Enternode server.jsThe server is running on port 3000. Open the browser and enterlocalhost:3000You can see a simple front-end page:

Query data:

Save data:

Query data again:

So far, a complete Ajax request demo is complete.

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.