jquery跨域Ajax请求

转自http://tonl.iteye.com/blog/1682394
关键:ajax的dataType为jsonp,并且在请求的url中加上"?jsoncallback=?"
前台代码:

<script type="text/javascript" src="jquery-1.7.2.min.js"></script>   
<script type="text/javascript">  
    function RegisterRequest2() {  
        /* getJSON method is ok also...   
        $.getJSON("http://192.168.1.154:7087/ClusterServer/Rigister?jsoncallback=?", { pwd: '123', username: 'tl' }, function(json) { alert(json.name); });   
        */  
           
        $.ajax({  
            url: "http://192.168.1.154:7087/ClusterServer/Rigister?jsoncallback=?",  
            type: "GET",  
            data: { pwd: '123', username: 'tl' },  
            dataType: "jsonp",  
            success: function(data) {  
                alert(data.name);  
            },  
            error: function(a, b, c) {  
                alert("error==" + b);  
            }  
  
        });   
    }    
</script>  
<input type="button" onclick="RegisterRequest2();"  value="StartRequest" />  

后台Servlet代码:
import java.io.IOException;  
  
import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
  
public class Rigister extends HttpServlet {  
  
    @Override  
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
            throws ServletException, IOException {   
        String pwd = req.getParameter("pwd");  
        String username =req.getParameter("username");  
        System.out.println("get=="+username+"  ==="+pwd);  
           
        String callback = req.getParameter("jsoncallback");   
        resp.getWriter().write(callback + "({name:'tzy',phone:'123'})"); //参数为json格式  
    }  
  
    @Override  
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
            throws ServletException, IOException {   
        String pwd = req.getParameter("pwd");  
        String username =req.getParameter("username");  
        System.out.println("post=="+username+"  ==="+pwd);  
           
        String callback = req.getParameter("jsoncallback");   
        resp.getWriter().write(callback + "({name:'tzy',phone:'123'})");   
    }  
  
}  

后台返回前台的时候取出jsoncallback回调函数名,将json格式的数据作为函数的参数,整个以字符串的形式返回给前台。

你可能感兴趣的:(java,html,Ajax,servlet)