javascript - http-Get 请求,响应为空

标签 javascript jquery ajax

我想用 JavaScript 处理 http 请求的响应。您可以在这里找到一个简单的示例。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1">
  <title>JavaScript Test</title>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  <script type="text/javascript">
    function serviceCall() {
      $.ajax({
        type: "GET",
        url: 'http://localhost:8181/geoserver/wfs?Service=WFS&Request=GetFeature&Version=1.0.0&typename=topp:tasmania_water_bodies&SRS=EPSG:4326',
//        url: 'http://demo.opengeo.org/geoserver/ows?Service=WFS&Request=GetFeature&Version=1.0.0&typename=topp:tasmania_water_bodies&SRS=EPSG:4326',
        complete: function(xml, status){
          alert(xml.responseText);
        }
      });
    }
  </script>
</head>
<body>
  <center><button onclick="serviceCall()">Start...</button></center>
</body>
</html>

该请求直接在浏览器中运行。通过 Ajax 和 JavaScript,响应为空。 Firebug 在第 1 行第 1 列报告 xml 解析错误。我尝试将请求发送到本地主机和远程服务器,但响应始终为空。我将不胜感激任何建议。

最佳答案

为什么不使用success而不是complete?因为 complete 总是被触发,即使它失败了,而 success 仅当它成功时才被触发。那么您不需要 xml, status

示例(自 CORS 起不再工作):

$.ajax({
    type: "GET",
    url: 'http://localhost:8181/geoserver/wfs?Service=WFS&Request=GetFeature&Version=1.0.0&typename=topp:tasmania_water_bodies&SRS=EPSG:4326',
    success: function(response){
      alert(response);
    }
  });

此外,如果您不想访问其他域。如果您拥有其他域,则可以使用 JSONP。否则不可能。

尝试将以下部分添加到 URL:&outputFormat=json&format_options=callback:processJSON

无工作 jQuery 示例(此处为实际示例: http://jsfiddle.net/QWgJa/ )

function loadJSON(url)
{
    var headID = document.getElementsByTagName("head")[0]; 
    var newScript = document.createElement("script");
    newScript.type = 'text/javascript';
    newScript.src = url;
    headID.appendChild(newScript);  
}
function processJSON(jsonData)
{
    alert(jsonData); 
}

loadJSON("http://demo.opengeo.org/geoserver/ows?Service=WFS&Request=GetFeature&Version=1.0.0&typename=topp:tasmania_water_bodies&SRS=EPSG:4326&outputFormat=json&format_options=callback:processJSON");

信息 URL

关于javascript - http-Get 请求,响应为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14384653/

相关文章:

javascript - 如何序列化与 jQueryUI 可排序列表的当前项相关的数据?

javascript - 如何在 tomcat 上部署 Vue.js 应用程序?

javascript - Iframe 中的表单按钮,单击时在父窗口中加载

javascript - jquery删除多个类

c# - 无法拆分文件并发送然后加入服务器

php - 每 x 秒自动刷新一个 Html 表

javascript - 如何从 DIV 中调用此脚本?

javascript - 没有选中属性的复选框

jquery - Bootstrap modal-body – 禁止使用 ESC 键或鼠标关闭

javascript - 突出显示代码镜像文本区域中的错误行