This time I will bring you three Ajax implementation methods and AJAX parsing JSON. What are theprecautionsfor 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 JSONString written in format.
Front page parameter input interface:
Html code
显示区域
name:
age:
1. Prototype implementation
Html code
In the Ajax implementation of prototype, use the evalJSON method to convert the string into a JSON object.
2. jquery implementation
Html code
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
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; }
2, the new Function form is quite weird.
function strToJson(str){ var json = (new Function("return " + str))(); return json; }
3, use the global JSON object.
function strToJson(str){ return JSON.parse(str); }
var str = '{name:"jack"}'; var obj = JSON.parse(str); // --> parse error
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!