Ajax发布并获得跨站点

时间:2016-02-24 07:35:28

标签: javascript jquery ajax cross-domain

我是一个新的jser,现在我在如何实现ajax POST和GET方面遇到了麻烦。我可以像get post那样通过谷邮递员发布和获取数据。

但是我无法通过jquery ajax获取数据,错误是'Uncaught SyntaxError:Unexpected token:'。它得到响应,但跳转到错误功能。我找到了很多解决方案,但是我可以实现POST和GET,而不像谷歌邮递员那样改变后台界面吗?

    $(function(){
    $.ajax({
        url: "http://115.29.203.53:10013/students",
        type: "GET",
        async: false,
        dataType: "jsonp",
        success: function(json){
            console.log(json);
        },
        error: function(){

        }
    });
});

感谢您阅读我的问题,请原谅我破碎的英语!

1 个答案:

答案 0 :(得分:0)

您要做的是使用ajax进行跨域访问。这是不可能的。您可以通过设置

来发出跨域请求
dataType : "JSONP"

但JSONP格式类似于functionname({" a":1,b:{c:2})。这意味着JSON对象应该在带有一些回调函数的花括号()中。因此,你得到了

"未捕获的SyntaxError:意外的令牌:"

为了进行跨域请求,需要添加Http标头('Access-Control-Allow-Origin: *')。然后,您就可以使用dataType JSON进行跨域请求。

你的AJAX看起来像这样。

 $(function () {
            $.ajax({
                url: "http://115.29.203.53:10013/students",
                type: "GET",
                async: false,
                dataType: "JSON",
                success: function (json) {
                    console.log(json);
                },
                error: function () {
                    console.log("Error");
                },
                crossDomain: true
            });
        });