无法在ajax网址中传递参数

时间:2014-06-13 04:09:02

标签: jquery html ajax wcf

我无法使用jQuery url将参数传递给wcf服务方法。

以下是我的服务合同:

namespace WcfService1
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [WebInvoke(Method = "GET", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest, UriTemplate = "/InsertData/?Name={Name}&Email={Email}&Category={Category}&Mobile={Mobile}&Message={Message}")]
        string InsertData(string Name, string Email, string Category, string Mobile, string Message);
    }   
}

我的jQuery代码:

$(document).ready(function (e) {
        $('#BtnRegister').click(function (e) {
            alert("hi");
            debugger;
            var name = document.getElementById('TxtUserName').value;
            var email = document.getElementById('TxtUserEmail').value;
            var category = document.getElementById('TxtUserCategory').value;
            var mobile = document.getElementById('TxtUserMobile').value;
            var message = document.getElementById('message').value;

            $.ajax({
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                url: 'http://localhost:22727/Service1.svc/InsertData/',
                data: { Name: UserName, Email: UserEmail, Category: UserCategory, Mobile: UserMobile, Message: UserMessage },
                async: false,
                success: function (response) {
                    alert("Record Has been Saved in Database");
                },
                error: function ()
                { console.log('there is some error'); }
            });
            e.preventDefault();
        });
    });

我无法调用服务方法来传递参数。请帮忙。

3 个答案:

答案 0 :(得分:2)

yippee的。我解决了我的问题。

我已通过以下网址:

url: 'http://localhost:22727/Service1.svc/InsertData/' + name + '/' + email + '/' + category + '/' + mobile + '/' + message,

答案 1 :(得分:0)

使用JSON.stringify序列化数据后尝试:

 $.ajax({
                type: 'POST',
                contentType: "application/json; charset=utf-8",
                url: 'http://localhost:22727/Service1.svc/InsertData/',
                data: JSON.stringify({ Name: UserName, Email: UserEmail, Category: UserCategory, Mobile: UserMobile, Message: UserMessage }),
                async: false,
                success: function (response) {
                    alert("Record Has been Saved in Database");
                },
                error: function ()
                { console.log('there is some error'); }
            });

答案 2 :(得分:0)

{ Name: UserName, Email: UserEmail, Category: UserCategory, Mobile: UserMobile, Message: UserMessage }

此处UserName是未定义的变量。使用您在代码中声明的变量,如下所示

{ Name: name, Email: email, Category: category, Mobile: mobile, Message: message }

希望它能正常工作