ajax請求之JSON.stringify__JSON

來源:互聯網
上載者:User

問題提出:確保背景程式無問題,通過postman能成功提交表單,但是從前台頁面用ajax提交卻始終執行error的回呼函數,debug一下,發現postman發送請求中攜帶的資料格式為json,但是debug前台頁面發送時時一串的attribute1=value1&attribute2=value2&...問題出在哪裡。

 

後台介面:

 

/*Controller請求url*/var url = "${ctx}/developer/register";/*約定資料格式*/consume=MediaType.APPLICATION_JSON_VALUE

json資料:

json_data = {                "loginName": loginName,                "password": password1,                "name": name,                "email": email,                "sex": sex,                "avatar": avatar,                "description": description            }

 

ajax請求代碼-方式一:

 

<span style="line-height: 1.5;">$.ajax({    type: "POST",    url: url,    contentType: "application/json",    dataType: "json",    data: json_data,    success: function () {          window.alert("添加開發人員成功");    },    error: function (XMLHttpRequest) {          alert("請求出錯:"+XMLHttpRequest.status+XMLHttpRequest.statusText);    } });</span>

ajax請求結果:每次都是執行error,錯誤碼:400,Bad Request。

ajax請求代碼-方式二:

 

$.ajax({    type: "POST",    url: url,    contentType: "application/json",    dataType: "json",    data: json_data,    success: function () {          window.alert("添加開發人員成功");    },    error: function (XMLHttpRequest) {          alert("請求出錯:"+XMLHttpRequest.status+XMLHttpRequest.statusText);    } });

ajax請求結果:彈出“添加開發人員成功“對話方塊,問題解決之。

 

原因:Controller和前台約定傳遞json格式的資料,因此前台ajax必須傳遞json格式的資料,通過查文檔知,data屬性接收的參數類型為String,因此要用JSON.stringify將json對象轉換成String類型。

 

附>>jQuery ajax方法連結:http://www.w3cschool.cn/ajax_ajax.html

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.