1. 程式人生 > >ajax跨域問題返回json資料

ajax跨域問題返回json資料

跨域提交:【和普通的提交只是前臺的jsonp後臺的返回方式稍微有點區別】

        $.ajax({
                url:"http://localhost:8080/xxx.action",
                type:"get",
                dataType:"jsonp",  //資料格式設定為jsonp

                jsonp:"callback",//後臺返回json需要用callback包起來
                data:{"searchNo":searchNo},
                async:"false",
                success:function(data){
                    if(data != null ){
                        //根據busyType跳轉頁面
                        //回填物件
                        if(data.code ==200){

                          alert(data.message);

                         //業務回填
                        }
                    }
                },
                beforeSend:function(){
                }
            });

後臺:

public void xxx.action(){

Stirng id = this.getRequest().getParameter("searchNo");

String callback = this.getRequest().getParameter("callback");

JSONObject json = new JSONObject();

if(StringUtils.isNotBlank(searchNo)){
            ........//業務

         
            json.put("code", 200);
            json.put("message", "success");
        }
          renderText(callback+"("+json.toString()+")");

}

同項目下普通的ajax提交:

        $.ajax({
                url:"http://localhost:8080/xxx.action",
                type:"get",
                dataType:"json",  //資料格式設定為jsonp
                data:{"searchNo":searchNo},
                async:"false",
                success:function(data){
                    if(data != null ){
                        //根據busyType跳轉頁面
                        //回填物件
                        if(data.code ==200){

                          alert(data.message);

                         //業務回填
                        }
                    }
                },
                beforeSend:function(){
                }
            });

後臺:

public void xxx.action(){

Stirng id = this.getRequest().getParameter("searchNo");

JSONObject json = new JSONObject();

if(StringUtils.isNotBlank(searchNo)){
            ........//業務

         
            json.put("code", 200);
            json.put("message", "success");
        }
        renderText(json.toString());

}

----------------------------------------------------------------------------------------------------------------------------------------------------》》》

可能出現情況,後臺返回的json方法,前臺一直跳轉到error的方法,不進入success方法

原因有兩種:

1、dataType的方式要確定是jsonp(跨域提交)還是json

2、ajax裡面引數url的頭地址要和訪問的系統頭地址要一樣,即使是localhost和127.0.0.1也會因為報錯而不進入success方法,進入error方法。