javascript - JQuery 的 Web 服务调用失败

标签 javascript jquery visual-studio-2005 asp.net-ajax web-services

非常感谢某人能够提供的任何帮助!

我一直在尝试设置对 Web 服务的 JQuery Ajax 调用,到目前为止我所做的一些调试表明 Web 服务将返回参数,并且从客户端我使用了警报功能显示数据将进入数据字符串,但后来我将其更改为根本不接受任何参数,但它仍然不起作用,即;什么也没有发生,什么也没有移动。我想知道“url:”或“data:”条目是否可能存在某种类型的语法错误,因为我在查看示例时以多种方式看到了它们。

使用支持 AJAX 的网页设置项目。

就像我之前说的——帮助!!

页面

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CS.aspx.cs" Inherits="_Default" %>
<%@ Import Namespace = "System.Web.Services" %>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Check User Name Page</title>
    <script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type = "text/javascript">

//function ShowAvailability() {

    $(document).ready(function() {
    $("#btnCheck").click(function(event){
    //alert(" '{" + userName: "' + $('#txtUserName').val() + "'}")
     // alert('{userName: "musser"}')
   $.ajax({
        type: "POST",
        url: "WebService.asmx/CheckUserName",
        data: "{}",

     //   data: '{userName: "musser"}',
        //data: '{userName: "' + $('#txtUserName').val() + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: OnSuccess,
        failure: function(response) {
            alert(response);

          }
      });
    });
 });
//}


function OnSuccess(response) {
    var mesg = $("#mesg")[0];

    switch (response) {
        case "true":
            mesg.style.color = "green";
            mesg.innerHTML = "Available";
            break;
        case "false":
            mesg.style.color = "red";
            mesg.innerHTML = "Not Available";
            break;
        case "error":
            mesg.style.color = "red";
            mesg.innerHTML = "Error occured";
            break;                     
    }
}
function OnChange(txt) {
   $("#mesg")[0].innerHTML = "";
}


</script>
</head>
<body>
    <form id="form1" runat="server">

        <div>
         UserName : 
    <asp:Textbox ID="txtUserName" runat="server" ></asp:Textbox>
    <input id="btnCheck" type="button" value="Show Availability"/>
    <br />
    <span id = "mesg"></span>
        </div>
    </form>
</body>
</html>

网络服务

using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

using System.Web.Script.Services;
using System.Web.Script.Serialization;
using System.Collections.Generic;






/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://localhost:1252/ChkUserNamesSite/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService()]

public class WebService : System.Web.Services.WebService
{
    public WebService()
    {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    [ScriptMethod(ResponseFormat= ResponseFormat.Json)]

    public static string CheckUserName(string userName)
    {
        string returnValue = string.Empty;
        try
        {
            string consString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
            SqlConnection conn = new SqlConnection(consString);
            SqlCommand cmd = new SqlCommand("spx_CheckUserAvailability", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@UserName", userName.Trim());
            conn.Open();
            returnValue = cmd.ExecuteScalar().ToString();
            conn.Close();
        }
        catch
        {
            //returnValue = "error";
            returnValue = userName;

        }
        return returnValue;

网络配置

<?xml version="1.0"?>
 <configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
 <configSections>
  <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
   <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
    <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
    <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">
     <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere"/>
     <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
     <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>
    </sectionGroup>
   </sectionGroup>
  </sectionGroup>
 </configSections>
  <connectionStrings>
    <add name ="conString" connectionString ="Server=Pandora;Database=dbUsers;Integrated Security=true"/>
  </connectionStrings >
 <system.web>

  <pages>
   <controls>
    <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
   </controls>
  </pages>
  <!--
          Set compilation debug="true" to insert debugging
          symbols into the compiled page. Because this
          affects performance, set this value to true only
          during development.
    -->
  <compilation debug="true">
   <assemblies>
    <add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
   </assemblies>
  </compilation>
  <httpHandlers>
   <remove verb="*" path="*.asmx"/>
   <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
   <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
   <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>
  </httpHandlers>
  <httpModules>
   <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  </httpModules>
 </system.web>
 <system.web.extensions>
  <scripting>
   <webServices>
    <!-- Uncomment this line to customize maxJsonLength and add a custom converter -->
    <!--
      <jsonSerialization maxJsonLength="500">
        <converters>
          <add name="ConvertMe" type="Acme.SubAcme.ConvertMeTypeConverter"/>
        </converters>
      </jsonSerialization>
      -->
    <!-- Uncomment this line to enable the authentication service. Include requireSSL="true" if appropriate. -->
    <!--
        <authenticationService enabled="true" requireSSL = "true|false"/>
      -->
    <!-- Uncomment these lines to enable the profile service. To allow profile properties to be retrieved
           and modified in ASP.NET AJAX applications, you need to add each property name to the readAccessProperties and
           writeAccessProperties attributes. -->
    <!--
      <profileService enabled="true"
                      readAccessProperties="propertyname1,propertyname2"
                      writeAccessProperties="propertyname1,propertyname2" />
      -->
   </webServices>
   <!--
      <scriptResourceHandler enableCompression="true" enableCaching="true" />
      -->
  </scripting>
 </system.web.extensions>
 <system.webServer>
  <validation validateIntegratedModeConfiguration="false"/>
  <modules>
   <add name="ScriptModule" preCondition="integratedMode" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  </modules>
  <handlers>
   <remove name="WebServiceHandlerFactory-Integrated"/>
   <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
   <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
   <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  </handlers>
 </system.webServer>
</configuration>

最佳答案

天哪,代码太多了!将来,我建议您专注于一两小段代码(在本例中,我会说 AJAX 调用和 Web 服务函数定义。)它使其更易于阅读,并且更有可能获得响应。

至于问题,您的网络服务定义表明它接受一个字符串(用户名),但您没有向它发送任何内容。这是一个错误,将阻止调用 Web 服务。您必须为所有函数参数发送适当的数据类型才能使其正常工作。如果您打算发送 null,请明确执行:{ userName: null }

关于javascript - JQuery 的 Web 服务调用失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1780868/

相关文章:

jquery - 多选下拉菜单 : Disable selected option only (jQuery)

javascript - Jquery toggle ('slide' ) 只滑动一次

visual-studio - 我需要运行 devenv.exe/setup 两次吗? [对比2005年和2008年]

c++ - 如何根据命中的另一个断点添加条件中断?视觉C++

c++ - XLL插件开发-Excel SDK函数问题

javascript - window.opener.parent 在 Microsoft Edge 上不起作用

JavaScript:在输入前一个数组中的所有单词后显示单词的下一个索引

javascript - socket.io, 'Access-Control-Allow-Origin' 错误

javascript - 基于动态生成的 DOM 元素运行脚本

javascript - 如何在js中创建多行字符串