通过ajax调用webservice方法

时间:2014-11-19 11:28:48

标签: javascript c# jquery ajax wcf

我有WCF服务方法:

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

我通过我的phonegap代码ajax调用此方法:

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

但服务方法没有被调用。

在“网络”标签上,它给出了错误:

enter image description here

在控制台上:

enter image description here

EDIT1:

当我将contenttyp更改为:appplication / json; charset = utf-8

enter image description here

2 个答案:

答案 0 :(得分:1)

http://api.jquery.com/jquery.ajax/

doc中的crossDomain点

检查一下,你发送跨域ajax。默认情况下不允许这样做。

答案 1 :(得分:1)

很可能是因为您传递的参数和WCF服务的返回类型。该方法应返回Object而不是bool。 .Net框架会自动将返回的对象转换为JSON字符串。

服务方:

    [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);
    }
});
相关问题