【问题标题】:AJAX - Cross-domain don't workAJAX - 跨域不起作用
【发布时间】:2014-04-17 20:03:01
【问题描述】:

我阅读了很多关于 json 可以很好地替代 XMLHttpRequests 的内容。我试过了,还是不行:

$.ajax({
crossDomain: true,
    url: settingsURL,
type: "POST",
dataType: 'JSONP',
parseAsHtml: true, cli: 'help',
    success: function(data) {
        data=$(data).find('div#TestDivContent');
        $('#TestDivContent').append(data);
    },
error: function() {
        $('#TestDivContent').append("<p>Can't Connect</p>");
    }
});

我得到...

Uncaught SyntaxError: Unexpected token < 

【问题讨论】:

  • 上述错误表示服务器响应不是JSONP而是HTML(或XML)。
  • 我很清楚是什么原因造成的。只需要一个解决方案。我不知道如何解决它。
  • 如果不能编辑服务端代码,我们把dataType改成'text'吧。
  • 如果我改变它我得到 XMLHttpRequest 错误
  • JSON 不是 XMLHttpRequests 的替代品,它们是不同的东西。这个帖子和你的问题有关:Loading cross domain html page with jQuery AJAX - 最后一个,支持https

标签: javascript jquery ajax cross-domain


【解决方案1】:

请检查下面的代码,它在跨域 () 中的作用就像一个魅力。 如果您同时控制两个域,即 Domain1.com 和 Domain2.com

//Ajax Script in Domain1.com
//No Conflict is the code snippet from my sample code You can delete it if not required no issues
<script type="text/javascript">jq1102 = jQuery.noConflict( true );</script>
<script type="text/javascript" >
    function jsonp(n){
        //GET Response is Here
        alert(n);
    }

    jq1102(function(){
        jq1102.ajax({
            type: "GET",
            dataType: "jsonp",
            url: 'http://domain2.com/ClientSiteApi/',
            crossDomain: true,
            complete: function(data){
                //Any Action You Like to Trigger After Complete 
            },
            error: function(jqXHR, textStatus, ex) {
                //Nothing to Change Here
            }
        });
    })
</script>

来自 Domain2.com 的回应

 echo 'jsonp("hello")'; //You Can place JSON string in replace of the Hello String

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-09
    • 2014-04-18
    • 1970-01-01
    • 1970-01-01
    • 2013-06-22
    • 1970-01-01
    • 1970-01-01
    • 2014-10-04
    相关资源
    最近更新 更多