ajax前台与后台的数据交互

时间:2022-01-01 19:24:36


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>