我想用 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/