Home Web Front-end JS Tutorial JavaScript native xmlHttp and jquery's ajax method json data format example_javascript skills

JavaScript native xmlHttp and jquery's ajax method json data format example_javascript skills

May 16, 2016 pm 03:27 PM

javascript version of ajax send request

(1) Create an XMLHttpRequest object. This object is the core of the ajax request and the information carrier of the ajax request and response. Different browsers have different creation methods

(2), request path

(3). Use the open method to bind and send a request

(4). Use the send() method to send a request

(5), Get the string returned by the server xmlhttpRequest.responseText;

(6), get the value returned by the server and store it in the form of xml object xmlhttpRequest.responseXML;

(7) Use W3C DOM node tree methods and attributes to inspect and parse the XML document object.

Preface:

Recently, as the project was launched and implemented, I had a little free time. In my spare time, I accidentally discovered what I had written before about the javascript native xmlHttp ajax method and the later jquery plug-in ajax method, so I made some summaries. Due to time reasons, it was not included in all Test on browsers. The currently tested ones are IE8, 9, 10, Google Chrome, Mozilla Firefox, and Opera. If you find any problems during the verification test, please give me feedback in time. Thank you all.

Back to business, let’s go directly to the code:

Front-end code

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Ajax练习</title>
  <script src="/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
  <style type="text/css">
  label{width:50px;display:inline-block;}
  </style>
</head>
<body>
<div id="contentDiv">
  <h2>html5表单元素</h2>
  <label>E-mail</label><input type="email" name="UserEmail" id="UserEmail" value="251608027@qq.com" /><br />
  <label>URL:</label><input type="url" name="UserURL" id="UserURL" value="http://www.baidu.com" /><br />
  <label>Number:</label><input type="number" name="UserNumber" id="UserNumber" min="1" max="100" value="87" /><br />
  <label>Range:</label><input type="range" name="UserRange" min="1" max="100" value="78" /><br />
  <label>Date:</label><input type="date" name="UserDate" id="UserDate" value="2015-12-01" /><br />
  <label>Search:</label><input type="search" name="UserSearch" id="UserSearch" value="search" /><br />
  <label id="lblMsg" style="color:Red; width:100%;"></label><br />
  <input type="button" id="btnXmlHttp" value="提 交" onclick="return xmlPost();" />
  <input type="button" id="btnAjax" value="Ajax提 交" onclick="return Ajax();" />
  <input type="button" id="btnPost" value="Post提 交" onclick="return Post();" />
  <input type="button" id="btnGet" value="Get提 交" onclick="return Get();" />
  <input type="button" id="btnGetJSON" value="GetJSON提 交" onclick="return GetJSON();" />
  <input type="button" id="btnCustom" value="Custom提 交" onclick="return Custom();" />
  <br /><label id="lblAD" style="color:Red; width:100%;">.NET技术交流群:70895254,欢迎大家</label>
  <script type="text/javascript">
    //基础数据
    var jsonData = {
      UserEmail: $("#UserEmail").val(),
      UserURL: $("#UserURL").val(),
      UserNumber: $("#UserNumber").val(),
      UserRange: $("#UserRange").val(),
      UserDate: $("#UserDate").val(),
      UserSearch: $("#UserSearch").val()
    };
    //统一返回结果处理
    function Data(data, type) {
      if (data && data.length > 0) {
        var lblMsg = "";
        for (i = 0; i < data.length; i++) {
          for (var j in data[i]) {
            lblMsg += j + ":" + data[i][j];
            if (j != "Name" && j != "UserSearch") { lblMsg += "," }
          }
          if (i != data.length) { lblMsg += ";"; }
        }
        $("#lblMsg").html(type + "请求成功,返回结果:" + lblMsg);
      }
    }
  </script>
  <script type="text/javascript">
    //javascript 原生ajax方法
    function createXMLHttp() {
      var XmlHttp;
      if (window.ActiveXObject) {
        var arr = ["MSXML2.XMLHttp.6.0", "MSXML2.XMLHttp.5.0", "MSXML2.XMLHttp.4.0", "MSXML2.XMLHttp.3.0", "MSXML2.XMLHttp", "Microsoft.XMLHttp"];
        for (var i = 0; i < arr.length; i++) {
          try {
            XmlHttp = new ActiveXObject(arr[i]);
            return XmlHttp;
          }
          catch (error) { }
        }
      }
      else {
        try {
          XmlHttp = new XMLHttpRequest();
          return XmlHttp;
        }
        catch (otherError) { }
      }
    }    
    function xmlPost() {
      var xmlHttp = createXMLHttp();
      var queryStr = "Ajax_Type=Email&jsonData=" + JSON.stringify(jsonData);
      var url = "/Handler/AjaxHandlerHelper.ashx&#63;no.=" + Math.random();
      xmlHttp.open('Post', url, true);
      xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      xmlHttp.send(queryStr);
      xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
          var data = eval(xmlHttp.responseText);
          Data(data, "javascript原生xmlHttp");
        }
      }
    }
  </script>
  <script type="text/javascript">
    //jquery $.ajax方法
    function Ajax() {
      $.ajax({
        url: "/Handler/AjaxHandlerHelper.ashx&#63;no.=" + Math.random(),
        type: "Post",
        async: false,
        data: {
          Ajax_Type: "Email",
          jsonData: JSON.stringify(jsonData)
        },
        dataType: "json",
        beforeSend: function () { //发送请求前 
          $("#btnPost").attr('disabled', "true");
        },
        complete: function () { //发送请求完成后
          $("#btnPost").removeAttr("disabled");
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
          alert("error!" + errorThrown);
          //alert("请求错误,请重试!");
        },
        success: function (data) {
          Data(data, "Jquery $.ajax");
        }
      });
    }
    //jquery $.post方法
    function Post() {
      $.post("/Handler/AjaxHandlerHelper.ashx&#63;no.=" + Math.random(),
        {
          Ajax_Type: "Email",
          jsonData: JSON.stringify(jsonData)
        },
        function (data) {
          Data(data, "Jquery $.post");
        }
      );
      }
    //jquery $.getJSON方法
    function GetJSON() {
      $.getJSON("/Handler/AjaxHandlerHelper.ashx&#63;no.=" + Math.random(),
        {
          Ajax_Type: "Email",
          jsonData: JSON.stringify(jsonData)
        },
        function (data) {
          Data(data, "Jquery $.getJSON");
        }
      );
      }
    //jquery $.get方法
    function Get() {
      $.get("/Handler/AjaxHandlerHelper.ashx&#63;no.=" + Math.random(),
        {
          Ajax_Type: "Email",
          jsonData: JSON.stringify(jsonData)
        },
        function (data) {
          Data(data, "Jquery $.get");
        }
      );
    }
  </script>
  <script type="text/javascript">
    //javascript原生脚本自定义jquery $.ajax方法
    var CustomAjax = function (custom) {
      // 初始化
      var type = custom.type; //type参数,可选      
      var url = custom.url; //url参数,必填      
      var data = custom.data; //data参数可选,只有在post请求时需要        
      var dataType = custom.dataType; //datatype参数可选      
      var success = custom.success; //回调函数可选
      var beforeSend = custom.beforeSend; //回调函数可选
      var complete = custom.complete; //回调函数可选
      var error = custom.error; //回调函数可选
      if (type == null) {//type参数可选,默认为get
        type = "get";
      }
      if (dataType == null) {//dataType参数可选,默认为text
        dataType = "text";
      }
      var xmlHttp = createXMLHttp(); // 创建ajax引擎对象
      xmlHttp.open(type, url, true); // 打开
      // 发送
      if (type == "GET" || type == "get" || type == "Get") {//大小写
        xmlHttp.send(null);
      }
      else if (type == "POST" || type == "post" || type == "Post") {
        xmlHttp.setRequestHeader("content-type", "application/x-www-form-urlencoded");
        xmlHttp.send(data);
      }
      xmlHttp.onreadystatechange = function () {
        if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
          if (dataType == "text" || dataType == "TEXT") {
            if (success != null) {
              //普通文本
              success(xmlHttp.responseText);
            }
          } else if (dataType == "xml" || dataType == "XML") {
            if (success != null) {
              //接收xml文档  
              success(xmlHttp.responseXML);
            }
          } else if (dataType == "json" || dataType == "JSON") {
            if (success != null) {
              //将json字符串转换为js对象 
              success(eval("(" + xmlHttp.responseText + ")"));
            }
          }
        }
      };
    };
    //自定义方法
    function Custom() {
      CustomAjax({
        type: "Post",
        url: "/Handler/AjaxHandlerHelper.ashx&#63;no.=" + Math.random(),
        data: "Ajax_Type=Email&jsonData=" + JSON.stringify(jsonData),
        dataType: "json",
        success: function (data) {
          Data(data, "Custom自定义");
        }
      });
    }
  </script>
</div>
</body>
</html> 
Copy after login

.ashx backend code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
namespace WebHTML5.Handler
{
  /// <summary>
  /// AjaxHandlerHelper 的摘要说明
  /// </summary>
  public class AjaxHandlerHelper : IHttpHandler
  {
    public void ProcessRequest(HttpContext context)
    {
      context.Response.ContentType = "application/json";
      //context.Response.Charset = "utf-8";
      var Ajax_Type = context.Request.QueryString["Ajax_Type"] == null &#63;
        context.Request.Form["Ajax_Type"] : context.Request.QueryString["Ajax_Type"];
      switch (Ajax_Type) 
      {
        case "Email":
          context.Response.Write(PostEmail(context));
          break;
        default:
          context.Response.Write("[{\"Age\":28,\"Name\":\"张鹏飞\"}]");
          break;
      }
    }
    public static string PostEmail(HttpContext context)
    {
      string semail = string.Empty;
      if (context.Request.HttpMethod == "GET")
      {
        semail = "[" + context.Request.QueryString["jsonData"] + "]";
      }
      else
      {
        semail = "[" + context.Request.Form["jsonData"] + "]";
      }
      return semail;
    }
    /// <summary>
    /// JSON序列化
    /// </summary>
    public static string JsonSerializer<T>(T t)
    {
      DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
      MemoryStream ms = new MemoryStream();
      ser.WriteObject(ms, t);
      string jsonString = Encoding.UTF8.GetString(ms.ToArray());
      ms.Close();
      return jsonString;
    }
    /// <summary>
    /// JSON反序列化
    /// </summary>
    public static T JsonDeserialize<T>(string jsonString)
    {
      DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
      MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
      T obj = (T)ser.ReadObject(ms);
      return obj;
    }
    public bool IsReusable
    {
      get
      {
        return false;
      }
    }
  }
} 
Copy after login

Jquery method extension

About Jquery method extension, you can google or Baidu by yourself;

Conclusion

Let me explain the situation: the value problem of the html5 range tag that appeared in the case is wrong. Don’t worry about it. You can google or Baidu on how to get the value of the range tag by yourself;

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

How do I debug JavaScript code effectively using browser developer tools? How do I debug JavaScript code effectively using browser developer tools? Mar 18, 2025 pm 03:16 PM

The article discusses effective JavaScript debugging using browser developer tools, focusing on setting breakpoints, using the console, and analyzing performance.

How do I use source maps to debug minified JavaScript code? How do I use source maps to debug minified JavaScript code? Mar 18, 2025 pm 03:17 PM

The article explains how to use source maps to debug minified JavaScript by mapping it back to the original code. It discusses enabling source maps, setting breakpoints, and using tools like Chrome DevTools and Webpack.

How do I use Java's collections framework effectively? How do I use Java's collections framework effectively? Mar 13, 2025 pm 12:28 PM

This article explores effective use of Java's Collections Framework. It emphasizes choosing appropriate collections (List, Set, Map, Queue) based on data structure, performance needs, and thread safety. Optimizing collection usage through efficient

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Getting Started With Chart.js: Pie, Doughnut, and Bubble Charts Mar 15, 2025 am 09:19 AM

This tutorial will explain how to create pie, ring, and bubble charts using Chart.js. Previously, we have learned four chart types of Chart.js: line chart and bar chart (tutorial 2), as well as radar chart and polar region chart (tutorial 3). Create pie and ring charts Pie charts and ring charts are ideal for showing the proportions of a whole that is divided into different parts. For example, a pie chart can be used to show the percentage of male lions, female lions and young lions in a safari, or the percentage of votes that different candidates receive in the election. Pie charts are only suitable for comparing single parameters or datasets. It should be noted that the pie chart cannot draw entities with zero value because the angle of the fan in the pie chart depends on the numerical size of the data point. This means any entity with zero proportion

See all articles