如何使用ajax jsonp将数据从一个域获取到另一个域?

时间:2015-12-10 04:28:41

标签: javascript jquery asp.net ajax

EX:我的网站网址"http://localhost:54887/CustomOrdering.html",但我想从其他网站"http://localhost:27746/Orders.aspx"获取数据。为此,我在CustomOrdering.html写了

function SessionLogin() {                    
                $.ajax({
                    type: "GET",
                    dataType: "jsonp",
                    contentType: "application/json",
                    async: false,
                    url: 'http://localhost:27746/Orders.aspx/SessionLogin',                       
                    success: function (msg) {
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert(errorThrown);
                    }
                }); 
            }     

Orders.aspx

 public  void SessionLogin()
    {
        HttpContext.Current.Response.ContentType = "application/json";
        string qs = HttpContext.Current.Request.QueryString["callback"];
        HttpContext.Current.Response.Write(qs+ "( [{ \"x\": 10, \"y\": 15}] )");
    }

我收到错误jQuery11110002214477863162756_1449484451326 was not called并在控制台中显示错误消息' Uncaught SyntaxError:Unexpected token<'并点击它指向Orders.aspx设计页面开始' error image

1 个答案:

答案 0 :(得分:0)

另一台服务器需要使用您给定的回调名称包装返回值:

 public  void SessionLogin()
    {
        HttpContext.Current.Response.ContentType = "application/json";
        string qs = HttpContext.Current.Request.QueryString["callback"];
        HttpContext.Current.Response.Write( qs + "( [{ \"x\": 10, \"y\": 15}] )");
    }