2013-01-17 57 views
1

我想用JavaScript处理http请求的响应。你可以在这里找到一个简单的例子。http-Get request with empty response

<!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解析错误。我尝试将请求发送到本地主机和远程服务器,但响应始终为空。我将不胜感激任何建议。

+0

您对响应内容有什么期待? – GreenRover

+2

http://en.wikipedia.org/wiki/Same_origin_policy – ManseUK

+2

你为什么要处理完成而不是ajax的成功事件? – ryadavilli

回答

1

为什么不使用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); 
    } 
    }); 

此外,如果你wan't访问不同的域。如果您拥有其他域,则可以使用JSONP。否则,这是不可能的。

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

工作无jQuery的例子(LIVE这里的例子: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

+0

一般正确;然而,[跨源资源共享](http://www.html5rocks.com/en/tutorials/cors/)(CORS)是服务器允许浏览器完成跨域Ajax请求的一种方式。这是一个比JSONP更清洁的解决方案(尽管旧版浏览器支持JSONP)。 – apsillers

+0

仍然JSONP是CORS的唯一解决方案。 – Niels

+0

恐怕不理解你的评论。 [CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing)和[JSONP](https://en.wikipedia.org/wiki/JSONP)是两种完全独立的方法来避免同源政策。 CORS使用特殊的服务器头,比如'Access-Control-Allow-Origin',它告诉浏览器如果请求来自一个特定的源,忽略同源策略。正如我所说的,CORS排除了一些较旧的浏览器,因为它需要一个支持CORS的浏览器。因此,JSON拥有最广泛的支持,但它不是唯一的解决方案。 – apsillers

相关问题