點選a 標籤實現post方式提交的兩種方式
阿新 • • 發佈:2019-01-04
在專案中遇到一個問題,就是點選a標籤,要實現以post方式提交。下面來總結一下解決方法。
一、
通過點選a標籤,讓form表單submit提交,從而實現post方式提交。下面看程式碼:
<a href="javascript:void(0);" onclick="document.getElementById('myform').submit();" id="agree" class="determine">
<form id="myform" method="post" action="url">
</form>
如果需要後臺返回一個json串,可以使用下列方法:
【com.google.gson.Gson;】
Gson gson=new Gson();
Map<String,Object> map = new HashMap<String,Object>();
map.put("code",100);
map.put("msg","success");
response.getWriter().write(gson.toJson(map));
【net.sf.json.JSONObject;】
JSONObject obj = new JSONObject(); obj.put("code",100); obj.put("msg","success"); response.getWriter().write(obj);
然而,有一個非常不便的地方就是,使用第一種方式,返回的json串,會在新的頁面開啟,前端頁面就無法通過這個json串來進行下一步操作了。
二、
第二種方法是通過ajax提交post方式的請求,為的是返回後臺的一個json值。如果需要獲得後臺返回的json值,並且,前端頁面要使用這個json串繼續進行操作,就可以使用第二種方法。
<a href="javascript:void(0);" id="agree" class="determine"/> $("#agree").on("click",function(event){ event.preventDefault();//使a自帶的方法失效$.ajax({ url:"url", type:"post", dataType:"json", data:{}, success:function(result){ if(result.code == 100) { } else { } }, error:function(){ alert("error!"); } });
這樣,就能獲得後臺傳送的json串,對前端程式碼進行操作了。