ajax前台与后台的数据交互

前端之家收集整理的这篇文章主要介绍了ajax前台与后台的数据交互前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。


action:

	public void testHttpUrl(){
		String testurl = getParameterSTR("testurl");
		Map<String,String> map = new HashMap<String,String>();
		 try {
				URL url = new URL(testurl);
				HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
				httpConn.setRequestMethod("POST");
				httpConn.setDoOutput(true);
				if(httpConn.getResponseCode() == httpConn.HTTP_OK){
					map.put("result","通过!~");  //此处value可传其他对象
				}
			} catch (Exception e) {
				map.put("result","HTTP接口配置有错,请仔细检查下~"); 
				e.printStackTrace();
			}
		JSONObject json = JSONObject.fromObject(map);
		try {
			servletResponse.setContentType("text/json;charset=utf-8");
			servletResponse.getWriter().write(json.toString());
			servletResponse.getWriter().close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

ajax:

<script type="text/javascript">
function testHttpUrl(str){
	url = str + "/services";
	 $.ajax({
		url:'serversAction!testHttpUrl.action',data:{testurl : url},type:"post",dataType:"json",success:function(data){
			alert(data.result);
		}
	}); 
	
}
</script>

猜你在找的Ajax相关文章