简体   繁体   中英

calling a wcf 4.0 service from jquery($.ajax)

I have a simple wcf service developed in vs2010

[ServiceContract]
public interface IService1
{

    [OperationContract]
    string GetData(int value);



    // TODO: Add your service operations here
}



public class Service1 : IService1
{
    public string GetData(int value)
    {
        return string.Format("You entered: {0}", value);
    }


}

the following call is working

    protected void Button1_Click(object sender, EventArgs e)
    {
        ServiceReference1.Service1Client p = new ServiceReference1.Service1Client();
        Label1.Text= p.GetData(5);
    }

but when I am trying to call it from jquery its not working

    $(".test").live("click", function () {
    $.ajax({
                type: "post",
                url: "http://localhost/Service1.svc/GetData",
                data: {value:'1'},
                contentType: "application/json; charset=utf-8",
                timeout: 10000,
                processData: true,
                dataType: "json",       
                success: function(d) {  
                alert(d);                                            
                    },
                    error:function (xhr, ajaxOptions, thrownError){
                        alert(xhr.status);
                         alert(thrownError.toString());
                    }
        });

can anybody pls help me coz its giving me sleepless nights. thanks in advance.

Sir,try this

$(".test").live("click", function () {
$.ajax({
            type: "post",
            url: "http://localhost/Service1.svc/GetData",
            data: "{'value':1}",
            contentType: "application/json; charset=utf-8",
            timeout: 10000,
            processData: true,
            dataType: "json",       
            success: function(d) {  
            alert(d);                                            
                },
                error:function (xhr, ajaxOptions, thrownError){
                    alert(xhr.status);
                     alert(thrownError.toString());
                }
    });

Check the data type of the JSON passed over the wire (using Fiddler2 or the developer tools of the browser of your choice). I suspect that the JSON is passing the "1" as a string instead of an integer.

It appears that the problem is in your data argument:

data: {value:'1'},

This should not have the single quotes around it. The service is trying to resolve to a method with a "value" variable with a string type. Do this instead:

data: {value:1},

That should help the service resolve to the right service method.

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