【问题标题】:Web Service call fails from JQuery来自 JQuery 的 Web 服务调用失败
【发布时间】:2025-12-03 13:45:01
【问题描述】:

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

我一直在尝试设置对 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>

【问题讨论】:

  • 只是一个警告:发布这么多代码通常被认为是错误的形式。这通常意味着您要么没有花时间了解问题,要么只是不想为我们解决问题。无论哪种方式,这都表明对那些可能愿意提供帮助的人缺乏尊重,这至少可以说是令人反感的。
  • 你试过使用本世纪的 JQuery 版本吗?我们现在在 1.10.2 上,并且 2.0.3 也可用。我认为 1.3 版不支持您正在尝试做的事情!

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


【解决方案1】:

天哪,代码太多了!将来,我会建议您专注于一两段代码(在这种情况下,我会说 AJAX 调用和 web 服务函数定义。)这样更容易阅读,更有可能得到响应。

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

【讨论】:

  • 我知道我应该把这个留给 .NET 的人。尝试从 jQuery 角度解决,但漏掉了缺席参数。
【解决方案2】:

看起来您正在返回一个字符串,而不是 JSON 对象。这应该做你想做的事:

$(document).ready(function() {
    $("#btnCheck").click(function(e){
        $.post("WebService.asmx/CheckUserName", {userName: "something"}, function(data, textStatus){
            OnSuccess(data); // Call your success method
        }, "text");
        e.preventDefault(); // Cancel any default actions on this button
    });
});

我建议使用Firebug 和 Firefox 进行故障排除。让控制台保持打开状态,单击#btnCheck。如果请求因某种原因失败(或成功),您可以打开请求详细信息,查看发送的内容和返回的内容。

编辑:您可能需要更改的唯一一件事是@Toji 建议的缺少的参数(我已经添加到我的答案中)。但是,我仍然会检查响应以查看您收到的是 JSON 字符串 ("username") 还是仅是文本字符串 (username)。

【讨论】:

    最近更新 更多