使用Ajax从jQuery调用WCF服务,但参数未通过。(ASP.NET)

时间:2015-10-03 08:46:54

标签: jquery asp.net ajax wcf

我正在开发Microsoft Visual Studio 2013社区版(WebForms,Visual Basic)。

在jQuery脚本中,使用Ajax调用WCF服务。

当我按下“LogInMe”按钮时,在“Function fnVerifyID(ByVal ID As String,ByVal PASS As String)”中,“ID”和“PASS”为“Nothing”。(我在firefox调试器中看到它。 )

但如果使用“data:{ID:”testID“,PASS:”testPASS“}”(在评论中),参数将按预期传递,由于某种原因。

【Test.aspx文件】

<%@ Page Title="" Language="vb" AutoEventWireup="false"     MasterPageFile="~/Site.Mobile.Master" CodeBehind="Test.aspx.vb" Inherits="Shop.Daishin" %>
    <%--<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" runat="server">
</asp:Content>--%>
<asp:Content ID="Content3" ContentPlaceHolderID="MainContent" runat="server">

<head>
    <!DOCTYPE html> 
<title>Test Title</title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css"/>
<link rel="stylesheet" href="css/custom.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
    <%--<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>--%>
<script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>
<script src="js/jCarousel.min.js" type="application/x-javascript" charset="utf-8"></script>
<script src="js/custom.js"></script>


    <script type="text/javascript">

    $(function () {

        $('#LogInMe').click(function () {

            var Para = '{ID: ' +  '"'+ $('#txtUserName').val() +'"'+ ', PASS: ' + '"'+ $('#txtPassword').val() + '"}'

            $.ajax({
                url: '/TestWCF.svc/fnVerifyID', 

                dataType: 'json', 
                contentType: "application/json; charset=utf-8",

                //data: { ID: "testID", PASS: "testPASS" },    // This is OK.
                data: Para,

                success: function (response) {
                        var obj = JSON.parse(response.d);            
                        alert(obj.Name)
                }, 

                error: function (xhr, status, err) {
                    alert('Exeption:');

                } 
            });

        });
    });

</script>

</head>
<body>

  <div data-role="page" data-add-back-btn="true" id="p-listview-thumbnail" >

        <div data-role="header" data-position="fixed" data-theme="d">
           <h1></h1>
            <a href="#Family" data-icon="gear" class="ui-btn-right" data-iconpos="notext" data-theme="d" >Options</a>   
            <input type="text" id="txtUserName" placeholder="Username" />
            <input type="password" name="passwordinput" id="txtPassword"  placeholder="Password" value=""  />
            <a href="javascript:Authenticate();" id="LogInMe" data-role="button" data-icon="check" data-iconpos="right">Log Me In!</a>
             <label for="basic_name" id="lblMessage"></label>            
        </div><!-- /content -->

</body>
</html>

【TestWCF.svc】

Imports System.ServiceModel
Imports System.ServiceModel.Activation
Imports System.ServiceModel.Web
Imports System.Web.Providers.Entities
Imports System.Runtime.Serialization.Json
Imports System.ServiceModel.Description
Imports System.Runtime.Serialization
Imports Newtonsoft.Json

<ServiceContract()>
Public Interface IService1

    <OperationContract()> _
        <WebInvoke(Method:="GET", ResponseFormat:=WebMessageFormat.Json)> _
    Function fnVerifyID(ByVal ID As String, ByVal PASS As String)

End Interface
<DataContract()> _
Public Class csVerifyID
    Dim sID As String
    Dim iFlg As Integer
    Dim sName As String


    <DataMember()> _
    Public Property Name() As String
        Get
            Return sName
        End Get
        Set(value As String)
            sName = value
        End Set
    End Property

End Class

<ServiceContract(Namespace:="")> _
<AspNetCompatibilityRequirements(RequirementsMode:=AspNetCompatibilityRequirementsMode.Allowed)>
Public Class DaishinWCF


    <WebGet()>
    Public Function fnVerifyID(ByVal ID As String, ByVal PASS As String)

        Dim Hyouji As String = CStr(ID) & CStr(PASS)

        Dim objVeryfyID As New csVerifyID

        objVeryfyID.Name = "Name"

        Dim person As String = JsonConvert.SerializeObject(objVeryfyID)

        Return person

    End Function
    <OperationContract()>
    Public Sub DoWork()
        ' Add your operation implementation here
    End Sub

End Class

1 个答案:

答案 0 :(得分:0)

试试这个:

var jData = {};
jData.ID = $('#txtUserName').val();
jData.PASS = $('#txtPassword').val();
$.ajax({
    crossDomain: true,
    cache: false,
    url: '/TestWCF.svc/fnVerifyID',
    contentType: "application/json; charset=utf-8",
    datatype: "json",
    data: JSON.stringify(jData),
    success: SuccessRslt,
    error: function (xhr, reason, ex) {
        var err = $.parseJSON(xhr.responseText);
        if (err != null && xhr.status.toString() != "0") {
            showerror('Error Code : ' + xhr.status + "\nError Message :" + xhr.statusText);
        }
    }
});