ajax post請求request.getParameter("")取值為null,ajax取值

來源:互聯網
上載者:User

ajax post請求request.getParameter("")取值為null,ajax取值

今天在寫提交一個json資料到後台,然後後台返回一個json資料類型。但是發現後台通過request.getParamter(“”)取到的值為null。

於是寫一個簡單的ajax 請求,來排查問題
前台代碼:

$(document).ready(function(){    $("#ajax").click(function(){        var depart="depart";        $.ajax({            url :path+ "/AjaxReponse",            data :"depart="+depart,            type : "post",            dataType : "json",                  success: function(data){                alert(data);            }        });    });});

後台代碼:

String depart=request.getParameter("depart");

現象:後台取到值為null。但是在google chrome調試工具調試時,request中已經有發送的值了

一.網友方法

正常的post請求(不包括ajax請求)在http頭中的content-type為application/x-www-form-urlencoded,這時在java後台可以通過request.getParameter(name)的形式擷取.但是通過原生ajax請求時,在java後台通過request.getParameter(name)的形式卻無法擷取到傳入的參數.
但是實際上在中可以看到,content-type已經是application/x-www-form-urlencoded的形式了。所以網友的方法不適用
http://m.blog.csdn.net/blog/eyebrother/36007145

二.編碼格式
既然在調試器中看到request的發送內容沒問題,那麼就是編碼格式的問題了。在後台添加代碼:
request.setCharacterEncoding(“utf-8”);
可以解決這個問題。
但是發現前台寫成這種類型

    data :{                "depart" : depart            },

後台取到的也是null。所以最終將js檔案編碼格式改為utf-8.解決這個問題

三.發送json類型資料到後台

$(document).ready(function(){    $("#ajax").click(function(){        var isReceipt = "1";        var adress ="2";        var reason = "3";        var projectInfo = {                "adress" : isReceipt,                "ownerDept" : {                    "deptCode" : adress            },                  "reason" : reason        };        $.ajax({            url :path+ "/AjaxReponse",            data :{                "depart" : JSON.stringify(projectInfo)            },            type : "post",            dataType : "json",                  success: function(data){                alert(data);            }        });    });});

後台:

String depart=request.getParameter("depart");Gson gson = new GsonBuilder().create();Depart dep = gson.fromJson(depart),        Depart.class);

前台通過JSON.stringify()方法將json類型轉換為string類型發送。
後台是使用google的GSON包,然後將json類型資料(String)轉換為實體類資料類型。

四.js 工具
由於js文法比較複雜,編譯器無法進行檢查。所以js代碼風格,錯誤比較難找。這裡推薦我使用的兩個工具。
1. JSTool
可以格式化js代碼
2. JSLINT
檢查語法錯誤
具體使用不詳述了,我都是下載這兩個工具對應的notepad++外掛程式。在notepad使用非常方便。

五. 吐槽
csdn 的新版部落格編輯器確實不錯,但是在寫部落格時沒有隨手儲存,開啟其他的csdn頁面時,提示markdown 編輯器執行個體已運行,必須重寫載入。然後整篇部落格都重寫了。實在是不能忍!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.