【问题标题】:Same origin policy violated?违反同源政策?
【发布时间】:2010-08-12 16:10:14
【问题描述】:

嘿嘿,
我正在使用 jQuery AJAX 调用从自托管 Web 服务(相同域)中提取数据,但它始终返回 0,这表明存在跨域问题。但这应该不是问题。

有什么建议可以解决这个问题吗?谢谢!

网站运行我的脚本

http://www.mysite.com/facebook/el_login   

我的 AJAX 调用:

var data = 'username=' + username.val() + '&password=' + password.val()
$.ajax({  
             url: "http://www.mysite.com/api/v01/account/exists.json",   
             type: "GET",        
             data: data,       
             cache: false,  
             complete: function(transport) {
              if(transport.status == 200) {
                  alert('Success');
              } else {
                  alert('Failed ' + transport.status );
              }
           }

         });  
  })

Firebug 请求标头:

Request Headersview source
Host    www.mysite.com
User-Agent  Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8
Accept  */*
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive  115
Proxy-Connection    keep-alive
Content-Type    application/x-www-form-urlencoded
X-Requested-With    XMLHttpRequest
Referer http://www.mysite.com/facebook/el_login
Cookie  sessionid=xxx

编辑:

好的,静态站点(同一服务器)上的 AJAX 调用似乎正在工作。我的 Web 服务后端基于 Django、Apache2 和 mod_wsgi .. 失败可能是有原因的。

【问题讨论】:

  • 看起来不错。您确定您一直在使用http://,而不是与https:// 混合使用吗?没有不同的端口?没有自动删除或添加www.?
  • 您是否尝试在回调中添加function(transport, textStatus) 并查看textStatus 是否提供更详细的信息?
  • textStatus 返回 null,表示请求中止。
  • 您是否尝试将 URL 粘贴到浏览器中以确认它是正确的?
  • 奇怪。这对我来说看起来不错。只是为了排除这种可能性,您的 hosts 文件中没有任何可能干扰的条目(例如,来自过去的服务器移动)?

标签: jquery ajax cross-domain


【解决方案1】:

对于调试我使用:

function showResponse(responseText, statusText, xhr, $form) {
    debugger; // TODO: Remove in production.
}

并在 ajax 调用中使用

error: showResponse

您是否尝试过使用以下参数:

        dataType: "json",
        contentType: "application/json; charset=utf-8",

【讨论】:

  • 如果我提供查询字符串,我的网络服务不需要内容类型
  • 他将“data”属性中的一个对象传递给jQuery
【解决方案2】:

好的,经过几个小时的星际争霸 2 想通了。
我用

连接了我的提交按钮
$('#submit').click(function ()

这似乎给 jQuery Ajax 带来了一些问题

解决方案:
使用“旧”样式连接您的 ajax 调用。

<input type="button" value="Submit" id="submit" onClick="sendLogin()"  />

function sendLogin() {  
  var query_data = { username:  'test', password:  'test'};

  $.ajax({  
             url: "http://www.mysite.com/api/v01/account/exists.json",   
             type: "POST",        
             data: $.toJSON(query_data),       
          dataType: 'application/json',
          contentType: 'application/json',
             complete: function(transport) {
             if(transport.status == 200) {
                  alert('Success');
              } else {
                  alert('Failed ' + transport.status );
              }
           }
         });  
}

【讨论】:

  • 奇数。如果您使用 $('#formID').submit(function... 并将输入类型更改为提交(并返回 false),它是否有效?
猜你喜欢
  • 1970-01-01
  • 2011-04-29
  • 2021-03-24
  • 2021-12-20
  • 2019-11-04
  • 2016-07-19
  • 2011-08-17
相关资源
最近更新 更多