Consuming web weather service in javascript

2019-07-28 17:28发布

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.

2条回答
狗以群分
2楼-- · 2019-07-28 17:53

There are a few problems there:

  1. Your URL should start with http://. Without it, the URL you have is resolved relative to the document the code is in.

  2. You're sending JSON in the POST. The odds are very high that the service doesn't expect to receive a POST containing JSON.

  3. You're expecting JSON back from the service, but it appears to reply with XML.

  4. 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.

查看更多
Melony?
3楼-- · 2019-07-28 18:11

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. 
查看更多
登录 后发表回答