问题
I would like to use javascript to consume the web weather service provided by cdyne. This is my code:
<html>
<head>
<title>weather app</title>
</head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script language="JavaScript">
function CallService() {
var DTO = "{ 'ZIP': '85281' }";
$.ajax({
type: "POST",
url: "wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityWeatherByZIP",
data: JSON.stringify(DTO),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (msg) {
alert(msg);
},
error: function (req, status, error) {
alert(req + "# " + status + "@ " + error);
},
complete: function (req, status) {
alert(req + "% " + status);
}
});
}
CallService();
</script>
</body>
</html>
When I ran the code, it shows the [object Object]#error@ and [object Object]%error in the alert, which means the error: function() and complete: function rather than success: function() are called. Is there anyone who used javascript to consume this weather service? Any help will be greatly appreciated.
回答1:
There are a few problems there:
Your URL should start with
http://
. Without it, the URL you have is resolved relative to the document the code is in.You're sending JSON in the POST. The odds are very high that the service doesn't expect to receive a POST containing JSON.
You're expecting JSON back from the service, but it appears to reply with XML.
You're trying to do a cross-origin call, but that's prevented by the Same Origin Policy, and the service you're trying to use doesn't appear to support Cross Origin Resource Sharing. (When I tried it fixing the issues above, I got the error saying that the cross-domain request wasn't allowed from my origin [which was
http:/jsbin.com
]).
Looking at the service description for the page you're trying to use, it doesn't look like it supports JSON-P, either, which means you can't use it from a different domain. You'll have to use a server-side process to query it.
回答2:
You cannot do ajax requests to a different domain, fiddle http://jsfiddle.net/wAt45/
XMLHttpRequest cannot load
http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityWeatherByZIP. Origin
http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.
来源:https://stackoverflow.com/questions/15451614/consuming-web-weather-service-in-javascript