AJAX - $.post(url,data,function,type)-2(参数为key:value(type-json))

前端之家收集整理的这篇文章主要介绍了AJAX - $.post(url,data,function,type)-2(参数为key:value(type-json))前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

上一篇http://www.jb51.cc/article/p-omnjnxei-bpe.html】的讲解传到后台的参数形式为username=yanshi02&password=123456 字符串。

那么如果传到后台的格式是JSON呢?【可能有人会问,如果参数形式为{mydata:username=yanshi02&password=123456}呢?我实在不理解,如果传字符串过来 ,你为何还要使用这种形式?字符串那么好解析!】

queryString = $('#editform').serializeArray();//object
queryString = JSON.stringify(queryString);//string

形式如下:
[{"name":"username","value":"admin"},{"name":"password","value":"123456"}]

$.post(url,{mydata:queryString},function(data){});

【JSP页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'post.jsp' starting page</title>

    <Meta http-equiv="pragma" content="no-cache">
    <Meta http-equiv="cache-control" content="no-cache">
    <Meta http-equiv="expires" content="0">    
    <Meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <Meta http-equiv="description" content="This is my page">
    <!-- <link rel="stylesheet" type="text/css" href="styles.css"> -->
    <script type="text/javascript" src="./scripts/jquery-1.7.2.js"></script>
    <script type="text/javascript"> var url =""; var queryString = ""; $(function(){ $("input[type='button']").click(function(){ url = $("#editform").attr("action"); //alert(url); //queryString = $('#editform').serialize(); queryString = $('#editform').serializeArray(); queryString = JSON.stringify(queryString);//string alert(queryString); //[{"name":"username","value":"yanshi02"},{"name":"password","value":"123456"}] $.post(url,function(data){ alert(typeof data+",返回的内容为 "+data); //var jsonReturn = this.data; //var jsonReturn = eval("("+data+")"); //var jsonReturn = $.parseJSON(data); var jsonReturn = JSON.parse(data);//将JSON字符串转换为对象 alert(typeof jsonReturn+" 转换后内容 "+jsonReturn); // 第一种json数组遍历方式 for(var i=0;i<jsonReturn.length;i++){ for(var key in jsonReturn[i]){ alert(key+':'+jsonReturn[i][key]); $("#content").append(jsonReturn[i][key]); } } } </script>
  </head>

  <body>
    This is my JSP page. <br>
    <form id="editform" action="postServlet3" method="post">
        <input type="text" name="username" value=""/>
        <input type="password" name="password" value=""/>

    </form>
    <input name="post" type="button" value="提交"/>
  </body>
</html>

后台接收】

package com.atgui.ajax.app.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;

import org.codehaus.jackson.map.ObjectMapper;

public class PostServlet3 extends HttpServlet {

    /** * Destruction of the servlet. <br> */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */
    public void doGet(HttpServletRequest request,HttpServletResponse response)
            throws ServletException,IOException {

        doPost(request,response);
    }

    public void doPost(HttpServletRequest request,IOException {

        response.setContentType("text/html");
        PrintWriter out = response.getWriter();

        String jsonStr = request.getParameter("mydata");
        System.out.println(jsonStr);
        ObjectMapper mapper = new ObjectMapper();

        String resultJson = mapper.writeValueAsString(jsonStr);
        System.out.println("resultJson ..."+resultJson);

        out.print(resultJson);  
        out.flush();
        out.close();
    }

    /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */
    public void init() throws ServletException {
        // Put your code here
    }

}

result as follows :

//获取的参数
[{"name":"username","value":"yanshi02"},"value":"123456"}]
//转换的JSON
resultJson ..."[{\"name\":\"username\",\"value\":\"yanshi02\"},{\"name\":\"password\",\"value\":\"123456\"}]"

题外话:

① 若不进行转换,直接返回out.println(jsonStr),那么页面可以正常解析data为[object object,object,object]—JSON数组对象;

  • 拿到返回的data【此时拿到的为json string】
  • 将字符串数组对象解析为JSON数组对象【解析为json object】
  • 正常遍历JSON数组对象!

② 若进行转换,返回out.println(resultJson),则不能正常解析为JSON数组对象进行遍历:

  • 拿到返回的data,type为string
  • 尝试进行JSON解析【失败,还是string】
  • 按照string字符串数组进行遍历!

Tips: 该文使用的是jackjson进行操作。无论前端页面或者后台,在接收或者解析json的时候注意 typeof json,究竟是字符串还是json object 或者是json 数组对象!!!!

原文链接:https://www.f2er.com/ajax/161437.html

猜你在找的Ajax相关文章