【问题标题】:GetServerDate with JSON protocol in JQuery, not budgingGetServerDate 与 JQuery 中的 JSON 协议,不让步
【发布时间】:2014-03-05 19:09:17
【问题描述】:

所以我正在尝试进行简单的 ajax 调用以从服务器上的文件中检索一些数据。我可以通过网络浏览器访问该文件,并且我已经按照关于这个主题的教程学习了 T,但它让我无处可去。 这是javascript代码:

<script type="text/JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
  type: "POST",
  url: "https://www.mychoicetechnologies.com/Services/FMSUtilities.asmx/GetServerDate",
  data: "{}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function (msg) 
  {        
     document.getElementById('area').innerHTML = "Success! Retrieved a server response using AJAX.";
  },
  error: function (xhr, status, error)
  {        
     document.getElementById('area').innerHTML =  "1." + error +   "<br>";
     document.getElementById('area').innerHTML += "2." + xhr +     "<br>";
     document.getElementById('area').innerHTML += "3." + status +  "<br>";
     document.getElementById('area').innerHTML += "The script has failed";
  }
});
</script>

当我运行这个脚本时,输出是:

1.

2.[对象对象]

3.错误

脚本失败。

【问题讨论】:

    标签: javascript jquery html ajax json


    【解决方案1】:

    当我在 Chrome 中运行它时,控制台显示:

    XMLHttpRequest 无法加载 https://www.mychoicetechnologies.com/Services/FMSUtilities.asmx/GetServerDate。请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,Origin 'http://fiddle.jshell.net' 不允许访问。 (索引):1

    这意味着您尝试访问的服务不允许来自其他域的请求。

    XMLHttpRequest cannot load, No 'Access-Control-Allow-Origin' header is present on the requested resource.

    编辑添加:

    使用GET 而不是POST 会更有意义,因为您只是在尝试阅读,而不是写作。而且服务返回的是 XML,而不是 JSON。

    【讨论】:

    • 谢谢,我现在正在考虑在服务器端使用 Access-Control-Allow-Origin 来允许我的脚本通过。如果我消除 dataType: "json" 这将成为 CORS 协议,对吗?
    • 我没有太多使用 CORS,但我的印象是它只依赖于 Origin/Access-Control-Allow-Origin 标头。 dataType 只会影响 JQuery 在响应返回后如何处理它。
    • 非常感谢,我已经妥善解决了这个问题。我的下一个问题是检索页面内容。 stackoverflow.com/questions/22227139/…
    猜你喜欢
    • 2016-12-19
    • 1970-01-01
    • 2020-04-15
    • 1970-01-01
    • 2017-03-06
    • 2012-11-13
    • 2015-07-06
    • 1970-01-01
    • 2011-02-26
    相关资源
    最近更新 更多