This time I will bring you three Ajax implementation methods and AJAX parsing JSON. What are the precautions for Ajax three implementation methods and AJAX parsing JSON? Here are practical cases, let’s take a look.
Preparation:
1、 prototype.js
2、 jquery1.3.2.min.js
3、 json2.js
Background processing program (Servlet), access path servlet/testAjax:
Java code
package ajax.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Ajax例子后台处理程序 * @author bing * @version 2011-07-07 * */ public class TestAjaxServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); String name = request.getParameter("name"); String age = request.getParameter("age"); System.out.println("{\"name\":\"" + name + "\",\"age\":\"" + age + "\"}"); out.print("{\"name\":\"" + name + "\",\"age\":" + age + "}"); out.flush(); out.close(); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request,response); } }
TestAjaxServlet receives two parameters: name and age, and returns a JSON String written in format.
Front page parameter input interface:
Html code
<p>显示区域</p> <p> name:<input><br> age:<input><br> </p>
1. Prototype implementation
Html code
<script></script> <script> function prototypeAjax() { var url = "servlet/testAjax";//请求URL var params = Form.serialize("parameters");//提交的表单 var myAjax = new Ajax.Request( url,{ method:"post",// 请求方式 parameters:params, // 参数 onComplete:pressResponse, // 响应函数 asynchronous:true }); $("show").innerHTML = "正在处理中..."; } function pressResponse(request) { var obj = request.responseText; // 以文本方式接收 $("show").innerHTML = obj; var objJson = request.responseText.evalJSON(); // 将接收的文本用解析成Json格式 $("show").innerHTML += "name=" + objJson['name'] + " age=" + objJson['age']; } </script> <input><br>
In the Ajax implementation of prototype, use the evalJSON method to convert the string into a JSON object.
2. jquery implementation
Html code
<script></script> <script></script> <input><br> <script> function jqueryAjax() { var user={"name":"","age":""}; user.name= $("#name").val(); user.age=$("#age").val(); var time = new Date(); $.ajax({ url: "servlet/testAjax?time="+time, data: "name="+user.name+"&age="+user.age, datatype: "json",//请求页面返回的数据类型 type: "GET", contentType: "application/json",//注意请求页面的contentType 要于此处保持一致 success:function(data) {//这里的data是由请求页面返回的数据 var dataJson = JSON.parse(data); // 使用json2.js中的parse方法将data转换成json格式 $("#show").html("data=" + data + " name="+dataJson.name+" age=" + dataJson.age); }, error: function(XMLHttpRequest, textStatus, errorThrown) { $("#show").html("error"); } }); } $("#submit").bind("click",jqueryAjax); // 绑定提交按钮 </script>
I’m new to jQuery, and I’m in json The processing is done with the help of json2.js. I also ask my seniors for advice. .
3. XMLHttpRequest implementation
##Html code
<script> var xmlhttp; function XMLHttpRequestAjax() { // 获取数据 var name = document.getElementById("name").value; var age = document.getElementById("age").value; // 获取XMLHttpRequest对象 if(window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); }else if(window.ActiveXObject){ var activxName = ["MSXML2.XMLHTTP","Microsoft.XMLHTTP"]; for(var i = 0 ; i < activexName.length; i++){ try{ xmlhttp = new ActiveXObject(activexName[i]); break; }catch(e){} } } xmlhttp.onreadystatechange = callback; //回调函数 var time = new Date();// 在url后加上时间,使得每次请求不一样 var url = "servlet/testAjax?name="+name+"&age="+age+"&time="+time; xmlhttp.open("GET",url,true); // 以get方式发送请求 xmlhttp.send(null); // 参数已在url中,所以此处不需要参送 } function callback(){ if(xmlhttp.readyState == 4){ if(xmlhttp.status == 200){ // 响应成功 var responseText = xmlhttp.responseText; // 以文本方式接收响应信息 var userp = document.getElementById("show"); var responseTextJson = JSON.parse(responseText); // 使用json2.js中的parse方法将data转换成json格式 userp.innerHTML=responseText + " name=" + responseTextJson.name + " age=" + responseTextJson.age; } } } </script> <input><br>
ps :Three ways to convert strings into JSON
During project development using Ajax, it is often necessary to return strings in JSON format to the front end, and the front end parses them into JS objects (JSON) .ECMA-262(E3) did not write the JSON concept into the standard, but in ECMA-262(E5) the concept of JSON was officially introduced, including the global JSON object and the Date toJSON method.
1, eval method analysis, I am afraid this is the earliest analysis method.
function strToJson(str){ var json = eval('(' + str + ')'); return json; }Remember the parentheses on both sides of str.
2, the new Function form is quite weird.
function strToJson(str){ var json = (new Function("return " + str))(); return json; }In IE6/7, when the string contains a newline (\n), new Function cannot parse it, but eval can.
3, use the global JSON object.
function strToJson(str){ return JSON.parse(str); }Currently IE8(S)/Firefox3.5/Chrome4/Safari4/Opera10 has implemented this method. When using JSON.parse, you must strictly abide by the JSON specification. For example, attributes need to be enclosed in quotation marks, as follows
var str = '{name:"jack"}'; var obj = JSON.parse(str); // --> parse errorname is not enclosed in quotation marks. When using JSON.parse, all browsers will throw Exception, parsing failed. The first two methods are fine. I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website! Recommended reading:
jQuery creates a vertical translucent accordion effect
jquery implements the navigation menu mouse prompt function
The above is the detailed content of Three Ajax implementation methods and AJAX parsing JSON. For more information, please follow other related articles on the PHP Chinese website!

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version
Visual web development tools

Notepad++7.3.1
Easy-to-use and free code editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft
