calling asmx web service method with jquery ajax

2019-06-06 23:07发布

问题:

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";
        }

    }
}

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>

Am I missing something?

回答1:

I think you're just running into a same origin policy.

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