Ajax即Asynchronous Javascript And XML(异步JavaScript和XML),是浏览器客户端向Web服务端异步数据传输HTTP请求的一种方式,Ajax请求可使网页从服务器请求少量的信息而不用更新整个页面,从而使WEB应用程序更小、数据交互速度更快,使用更友好。
一、客户端JavaScript使用GET方式向服务端提交Ajax请求,接收服务端的回应
function MyGetAjax() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://192.168.1.211/HttpReader.ashx?commandname=piccreadex&commanddata=170000000001FFFFFFFFFFFF', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
var response = xhr.responseText;
console.log(response);
} else {
alert("获取服务端的读卡指令失败!");
}
};
xhr.send();
二、客户端JavaScript使用POST方式向服务端提交Ajax请求,接收并解析服务端回应的Json数据
function readcard() {
var xhr = new XMLHttpRequest()
xhr.onreadystatechange = function(){
if (this.readyState == 4) {
if (this.status == 200) {
console.log("服务端回应数据:"+xhr.responseText);
var obj = JSON.parse(xhr.responseText);
if (obj.Code=="0"){ //成功获取到后台服务发送过来的已加密的指令码
let commdata=stringToASCII(obj.Data);
for (i=0;i<commdata.length;i++){
console.log(commdata[i]);
}
}
} else {
alert("获取服务端的读卡指令失败!");
}
}
}
xhr.open("POST", "http://192.168.1.211/HttpReader.ashx", true)
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.send("commandname=piccreadex&commanddata=170000000001FFFFFFFFFFFF");
}
三、服务端C#接收客户端提交的请求,解析获取提交参数,并回应请求
<%@ WebHandler Language="C#" Class="ReaderAPI" %>
using System;
using System.Web;
using System.IO;
using System.Security.Cryptography;
using System.Text;
public class ReaderAPI : IHttpHandler
{
private static readonly byte[] Key = Encoding.UTF8.GetBytes("GuangzhouRongShiElectron"); // 3DES 24字节密钥,长度必须=24
private static readonly byte[] IV = Encoding.UTF8.GetBytes("3DESEncr"); // 3DES 8字节初始化向量,长度必须=8,
public void ProcessRequest(HttpContext context)
{
string commandname = ""; //指令名称
string commanddata = ""; //指令代码
context.Response.ContentType = "text/plain";
context.Response.Headers.Add("Access-Control-Allow-Origin", "*"); //表示支持跨源交互数据
if (context.Request["commandname"] != null) { commandname = context.Request["commandname"].ToString(); }
if (context.Request["commanddata"] != null) { commanddata = context.Request["commanddata"].ToString(); }
if (commandname == "" && commanddata == "") //如果未接收到有效的Request信息,再尝试用Json解析是否有Request信息
{
StreamReader sr = new StreamReader(context.Request.GetBufferlessInputStream());
string response = sr.ReadToEnd();
commandname = getjsonval(response, "commandname");
commanddata = getjsonval(response, "commanddata");
}
string jsonText = "{\"Response\":\"json\"";
switch (commandname)
{
case "piccreadex":
if (HexToAscii(commanddata) == "")
{
jsonText = jsonText + ",\"Code\":\"1002\"" + ",\"Msg\":\"" + "Parameter error\"" + ",\"Data\":\"null\"}";
}
else
{
string desstr = TripleDESEncrypt(HexToAscii(commanddata));
jsonText = jsonText + ",\"Code\":\"" + "0\"";
jsonText = jsonText + ",\"Msg\":\"" + "Successful\"";
jsonText = jsonText + ",\"Data\":\"" + desstr + "\"}";
}
break;
default:
jsonText = jsonText + ",\"Code\":\"" + "1001\"";
jsonText = jsonText + ",\"Msg\":\"" + "Invalid request\"";
jsonText = jsonText + ",\"Data\":\"null\"}";
break;
}
context.Response.ContentType = "application/json";
context.Response.Write(jsonText);
}
//解析JSON数据=============================================================================
public static string getjsonval(string totalstr, string namestr)
{
string valustr = "";
totalstr = totalstr.Replace("{", "");
totalstr = totalstr.Replace("}", "");
totalstr = totalstr.Replace("\"", "");
string[] dataArray = totalstr.Split(new char[2] { ',', ',' });
if (dataArray.GetUpperBound(0) > 0)
{
for (int i = 0; i < dataArray.Length; i++)
{
string[] dataArray2 = dataArray[i].Split(new char[2] { ':', ':' });
if (dataArray2[0] == namestr)
{
valustr = dataArray2[1];
break;
}
}
}
return valustr;
}
public bool IsReusable
{
get
{
return false;
}
}
}
|