使用jquery ajax调用asmx Web服务方法 [英] calling asmx web service method with jquery ajax

查看:224
本文介绍了使用jquery ajax调用asmx Web服务方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在IIS 7.5中使用简单的asmx Web服务托管了Web应用程序

I have hosted web application with simple asmx web service in IIS 7.5

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace TestWebService
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class Test : System.Web.Services.WebService
    {
        [WebMethod]
        public static string HelloWorld()
        {
            return "Hello World";
        }

    }
}

当我单击 http://localhost/Test/Test.asmx中的调用按钮?op = HelloWorld 它工作正常,但是当我尝试使用$ .ajax()调用此方法时来自在ASP.NET开发服务器上运行的不同的Web应用程序项目( http:// localhost:1756 / HTMLPage1.htm )我得到一个错误response.status为0和不能调用web方法,这是我的代码。

when I click invoke button in http://localhost/Test/Test.asmx?op=HelloWorld it works fine but when I try to call this method by using $.ajax() from diffrent web application project which is running on ASP.NET development server (http://localhost:1756/HTMLPage1.htm) I got an error response.status as 0 and can't call the web method and here's my code.

<!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>
    <title>Consume Test </title>
    <script src="jquery-1.5.1.js" type="text/javascript"></script>
    <script type="text/javascript">

        function displayMessageCall() {

            $.ajax({
                type: "POST",
                url: "http://localhost/Test/Test.asmx/HelloWorld",
                data: '{}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: successMsg,
                error: errorMsg

            });
        }

        function successMsg(response) {
            alert('Success');
        }

        function errorMsg(response) {
            alert(response.status + " " + response.statusText)
        }

        $(document).ready(function () {
            displayMessageCall();
        });
    </script>
</head>
<body>
</body>
</html>

我错过了什么吗?

推荐答案

我认为你刚刚遇到同源政策

由于端口的不同,浏览器限制了javascript到达webservice。当然,有一些变通办法

Because of the port difference, the browser is restricting the javascript from reaching the webservice. Of course, there are some workarounds.

这篇关于使用jquery ajax调用asmx Web服务方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆