通过AJAX调用Web服务方法方法、AJAX、Web

2023-09-10 22:07:40 作者:少年多梦不多心

我有WCF服务的方法:

I have WCF service method:

[WebInvoke(Method = "POST", UriTemplate = "validateLogin", ResponseFormat = WebMessageFormat.Json,RequestFormat=WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.Bare)]
[OperationContract]
bool validateLogin(Login objLogin);

我通过我的PhoneGap code阿贾克斯调用这个方法:

I am calling this method through my phonegap code ajax as:

var parameters = {
    "EmailID": EmailID,
    "Password": Password
};

$.ajax({
    url: "http://localhost:95/MobileEcomm/Service1.svc/validateLogin",
    data: JSON.stringify(parameters),
    contentType: "text/xml;charset=utf-8",
    dataType: "json",
    headers: { 
        SOAPAction: '' 
    }, 
    type: 'POST',   
    processdata: false,
    cache: false,
    success: function (Data) {
        alert("asdsad");
    },
    error: function (response) {
        var value = JSON.stringify(response);
        alert("Error in Saving.Please try later."+value);
    }
});

但服务方法不获取调用。

But service method is not getting called.

在网络选项卡它给了我错误:

On Network tab it gives me error:

和控制台上:

EDIT1:

当我改变contenttyp为:参加办法/ JSON;字符集= UTF-8

When i change contenttyp to :appplication/json;charset=utf-8

推荐答案

。这个方法应该返回对象,而不是布尔。在.NET框架将返回的对象自动为您转换成JSON字符串。

Most probably because of Parameters which you are passing and return type of WCF service. The method should return Object instead of bool. The .Net framework will convert the returned object to the JSON string automatically for you.

服务端:

    [WebInvoke(Method = "POST", UriTemplate = "validateLogin", ResponseFormat = WebMessageFormat.Json,RequestFormat=WebMessageFormat.Json,BodyStyle=WebMessageBodyStyle.Bare)]
    [OperationContract]
    Object validateLogin(String Email, String Password)
        {
           //Do your stuff return bool value
        }

AJAX调用:

$.ajax({
    url: "http://localhost:95/MobileEcomm/Service1.svc/validateLogin",
    data: function ( {
              return JSON.stringify({
                Email: "abc@xyz.com",
                Password: "XXXXXXXXXX"
               });
             },
    contentType: "text/xml;charset=utf-8",
    dataType: "json",
    headers: { 
        SOAPAction: '' 
    }, 
    type: 'POST',   
    processdata: false,
    cache: false,
    success: function (Data) {
        alert("asdsad");
    },
    error: function (response) {
        var value = JSON.stringify(response);
        alert("Error in Saving.Please try later."+value);
    }
});