简体   繁体   中英

Consuming WCF service in Javascript/Jquery Ajax call

I have a WCF service hosted/published on the below path -

newslettersubscriptiondev.mercola.com/NewsletterSubscriptionService.svc

Want to call above WCF service in Jquery Ajax Call

Code written in jQuery -

<script type="text/javascript" src="JS/jquery-2.1.4.js"></script>
<script type="text/javascript" src="JS/jquery-2.1.4.min.js"></script>
<script type="text/javascript">
    function cityClickJQuery() {
        $.ajax({
            type: "POST",
            url: "http://newslettersubscriptiondev.mercola.com/NewsletterSubscriptionService.svc/CheckEmailaddressValidateOnly",
            data: { EmaillAddress: 'pranav.bilurkar28@gmail.com', Source: 'ArticleBody' },
            processData: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                alert('success');
                alert(data.d);
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(JSON.stringify(jqXHR));
                console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
                alert(jqXHR);
            }
        });
    }

</script>

In the above JS code CheckEmailaddressValidateOnly is the C# method defined in Service which requires 2 parameters.

Design code -

    <body>
        <form id="form1" runat="server">
        <div>
        <asp:Button ID="btn1" runat="server" OnClientClick="cityClickJQuery();" Text="click" />
        </div>
        </form> 
  </body>

Above JS code is not working.

Please Help.

First you should verify that you include attribute

[WebInvoke (ResponseFormat = WebMessageFormat.Json)]

Second you should use

data:JSON.stringify({EmaillAddress: 'pranav.bilurkar28@gmail.com', Source: 'ArticleBody'}), 

The JSON.stringify is defined in http://www.json.org/js.html .

One more update After the successful return of data you will see that the data returned back should be accessed not with data.d.EmailAddress , but with data.EmailAddress instead. ASMX web-service place the data in the property d, but not WCF service.

更改data: { EmaillAddress: 'pranav.bilurkar28@gmail.com', Source: 'ArticleBody' }, To

data: JSON.stringify({ EmaillAddress: 'pranav.bilurkar28@gmail.com', Source: 'ArticleBody' }),

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM