Front and rear end separation (ii)

Source: Internet
Author: User

First, the database city

One table cities, four fields PName, CName, Cnote, CImage

Second, JavaScript basics

1. Get and set the value of the element

The Value property of a text box commonly used for <input type= "text"/>,<textarea> is the values entered, which are passed in the DOM:

document.getElementById ("id"). value;

To get the value of the element with the set ID, for example:

Set the value of id= "province" to "Guangdong";

document.getElementById ("Province"). Value= "Guangdong";

Gets the value of "province" of value id=;

var V=document.getelementbyid ("province"). Value;

2. Get and set the innerHTML property value of the element

The innerHTML property of commonly used <div>,<span> elements is the displayed value, which is passed in the DOM:

document.getElementById ("id"). InnerHTML;

To get the value of the element with the set ID, for example:

The value of setting id= "MSG" to innerHTML is "Guangdong";

document.getElementById ("msg"). innerhtml= "Guangdong";

Gets the value of the innerHTML of the id= "MSG";

var V=document.getelementbyid ("msg"). InnerHTML;

Third, the JSON Foundation

Converting an object to a JSON-formatted string becomes the object's serialization, and an object can only be serialized into a string before it is transmitted over the network. In turn, a received JSON string must be converted to an object to be used in the program, a process known as JSON string deserialization.

Four, DEMO

Description: This demo function is to click the Submit button on the front page, the front page will be submitted to the data into JSON format, and then through the AJAX transfer JSON data to the background, after accepting the data after the JSON string is deserialized into the object, and then inserted into the database, If the insert succeeds then print the successful insert on the front page.

Client.html

<! DOCTYPE html>
Server.ashx

<%@ WebHandler language= "C #" class= "Demo.server" debug= "true"%>using system;using system.web;using System.Data; Using system.data.sqlclient;using newtonsoft.json;using newtonsoft.json.linq;namespace DEMO{public class Server:ihtt        Phandler {private SQLHelper SQLHelper = null;         Initialize public server () {sqlhelper = new sqlhelper ();            } public bool IsReusable {get {return false; }} public void ProcessRequest (HttpContext context) {//Receive S String s=context.            Request.querystring["S"]; Context.            Response.ContentType = "Application/json"; Context.            Response.Cache.SetCacheability (Httpcacheability.nocache); using (var reader = new System.IO.StreamReader (context). Request.inputstream))//{//String s = reader.            ReadToEnd (); if (!string.     IsNullOrEmpty (s))       {////Business process//}//}//string s = CONTEXT.R Equest.            Querystring["S"];            s = System.Web.HttpUtility.UrlDecode (s);            Converts a JSON string to an object//jobject Jobject = (jobject) jsonconvert.deserializeobject (s); Jarray jar = Jarray.parse (jobject["Rtdatasets"].            ToString ());                  Jobject Jobject = Jobject.parse (s);            Receive province parameter String p = (string) jobject["province"];            Receive City parameter String c = (string) jobject["City"; Context.            Response.Clear (); Context.            Response.ContentType = "Text/plain"; Context.            Response.Write (P + "" + C); Context.            Response.Flush (); if (Insert (P, c)) {context. Response.Write ("Add" ("+p+", "+c+") Success!             "); } else {context. Response.Write ("Add (" + P + "," + C + ") failed!             ");    }        }    Insert Function public bool Insert (string pname,string cName) {BOOL flag = false;            String sql = "INSERT INTO cities (pname,cname) VALUES (@pName, @cName)"; Sqlparameter[] para = new sqlparameter[]{new SqlParameter ("@pName", PName), New SqlParameter ("@cName            ", CName)}; int res = SqlHelper.            ExecuteNonQuery (SQL, para);            if (Res > 0) {flag = true;                    } return flag; }    }}

SQLHelper.cs

/* * AUTHOR:H * TIME:2015/5/30 16:50:04 * Explain: Database helper class */using system;using system.collections.generic;using Sy Stem. Linq;using system.text;using system.threading.tasks;using system.data;using system.data.sqlclient;using        System.configuration;namespace demo{public class SQLHelper {private SqlConnection conn = null;        Private SqlCommand cmd = null;        Private SqlDataReader SDR = null; Public SQLHelper () {String connstr = configurationmanager.connectionstrings["ConnStr"].            ConnectionString;        conn = new SqlConnection (CONNSTR); Private SqlConnection Getconn () {if (conn. state = = connectionstate.closed) {Conn.            Open ();        } return conn; }///<summary>///Execute SQL +/-change with parameters////</summary>//<param name= "SQL" > Additions/deletions/changes S QL statements </param>///<param name= "para" > Parameter set </param>///lt;returns></returns> public int ExecuteNonQuery (String sql, sqlparameter[] para) {int            Res using (cmd = new SqlCommand (SQL, Getconn ())) {cmd.                Parameters.addrange (para); res = cmd.            ExecuteNonQuery ();        } return res; }///<summary>///Execute SQL queries with parameters///</summary>//<param name= "SQL" >sql statements &L t;/param>//<param name= "para" > Parameter collection </param>//<returns></returns> Publ            IC DataTable ExecuteQuery (String sql, sqlparameter[] para) {DataTable dt = new DataTable ();            cmd = new SqlCommand (SQL, Getconn ()); Cmd.            Parameters.addrange (para); using (SDR = cmd. ExecuteReader (commandbehavior.closeconnection)) {dt.            Load (SDR);        } return DT; }    }}
The database has been given at the beginning of the article and will not repeat it here.


Front and rear end separation (ii)

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.