如何在asp.net mvc 5中使用ajax调用webservices

时间:2016-08-01 14:11:28

标签: javascript html asp.net asp.net-web-api

我正在使用asp.net mvc 5,我想在其中使用web api,我使用jquery库和下面的代码。但是我没有得到正确答案。返回总是失败但我可以看到输出browser.please帮帮我

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="js/jquery-1.12.4.js"></script>
    <script>

         function ftoken() {


             $.ajax({

                 url: 'http://charter724.ir/webservice/get_city_a.php?id=367&key=EmlyCD8JOWX22cL8IuNBju5K5',
                // data: {  },
                 type: 'GET',
                 dataType: 'json',
                 success: function (data) {
                     alert('success')
                    //   alert(data.data)
                     //if (country_id != "" && zone_code != "" && duration != "" && birthday != "") {
                     //    fPrice(data.token);
                     //}
                     //$.each(data, function (idx, result) {
                     //    alert(result.data);
                     //})
                 },
                 error: function (x, y, z) {
                     alert('fail')
                     //alert(x.responseText);
                     //alert(z);
                 }
             });

         }
    </script>
</head>
<body>
    <input type="submit" name="name" onclick="ftoken();" value="Click " />
</body>
</html>

I can see the output in the browser

1 个答案:

答案 0 :(得分:0)

由于Same Origin Policy,您将无法对此URL进行AJAX调用(是的,您可以在浏览器中复制并粘贴URL并获得响应,但您无法通过javascript访问它)。

同源策略规定只有来自同一域的AJAX调用才会被允许,你做的是这样的事情:

http://localhost...http://charter724...进行AJAX调用 - 这是不允许的

如果您检查浏览器控制台,您将看到类似于下面的错误:

XMLHttpRequest无法加载http://charter724.ir/webservice/get_city_a.php?id=367&key=EmlyCD8JOWX22cL8IuNBju5K5。 No&#39; Access-Control-Allow-Origin&#39;标头出现在请求的资源上。起源&#39; http://localhost:10585&#39;因此不允许访问

解决此问题的唯一方法是与公司联系,公开charter724服务并要求他们启用CORS(Cross Origin Resource Sharing)并允许来自您域的所有请求访问其服务电话。

或者,您可以使用HttpClient访问服务呼叫并获取JSON响应。如果您真的想要,您甚至可以公开自己的一组服务,这些服务与外部服务通信并访问您的来自java脚本的服务调用:

public async System.Threading.Tasks.Task<ActionResult> Index()
{
    string url = "http://charter724.ir/webservice/get_city_a.php?id=367&key=EmlyCD8JOWX22cL8IuNBju5K5";
    System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
    System.Net.Http.HttpResponseMessage response = await client.GetAsync(url);
    response.EnsureSuccessStatusCode();
    string responseBody = await response.Content.ReadAsStringAsync();

    return View();
}