0

누군가가 제공 할 수있는 도움에 정말 감사드립니다!JQuery에서 웹 서비스 호출이 실패합니다.

나는 웹 서비스에 대한 JQuery Ajax 호출을 설정하려고 시도 해왔다. 그리고 내가 해왔 던 작은 디버깅은 웹 서비스가 매개 변수를 반환하고 클라이언트 측에서 경고를 사용함을 보여준다. 함수는 데이터가 데이터 문자열로가는 것을 보여주기 위해 함수를 호출하지만, 매개 변수를 전혀 사용하지 않도록 변경했습니다. 여전히 작동하지 않습니다. 아무것도 일어나지 않고 아무것도 움직이지 않습니다. 나는 '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; 

웹 설정이 아닌 문자열 JSON 객체를 반환하는 것 같습니다

<?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> 
+2

경고 : 일반적으로이 많은 코드를 게시하는 것은 나쁜 형식으로 간주됩니다. 그것은 보통 당신이 문제를 이해할 시간을 가지지 않았거나 우리를 위해 문제를 이해하지 못한다는 것을 의미합니다. 어느 쪽이든, 기꺼이 도울 수있는 사람들에 대한 존경심이 부족하다는 것을 보여줍니다. –

+0

이번 세기의 JQuery 버전을 사용해 보셨습니까? 우리는 현재 1.10.2에 있으며 2.0.3도 사용할 수 있습니다. 나는 버전 1.3이 당신이하려고하는 것을 지원한다고 생각하지 않는다! – Jasmine

답변

0

. 이것은 당신이 원하는 일을해야합니다

$(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와 파이어 폭스를 사용하는 것이 좋습니다 것입니다. 콘솔을 열린 상태로두고 #btnCheck을 클릭하십시오. 어떤 이유로 요청이 실패한 경우 (또는 성공할 경우) 요청 세부 정보를 열어 전송 된 내용과 반환 된 내용을 볼 수 있습니다.

편집 : 변경해야 할 수도있는 것은 @Toji가 제안한 누락 매개 변수입니다 (이후 내 대답에 추가되었습니다). 그러나 응답을 확인하여 JSON 문자열 ("username") 또는 텍스트 문자열 (username)이 있는지 확인합니다.

2

코드가 많습니다. 앞으로는 하나 또는 두 개의 작은 코드 (이 경우 AJAX 호출과 webservice 함수 정의를 말할 것입니다)에 중점을 두도록 권합니다.이 코드는 읽기 쉽고 응답을받을 가능성이 높습니다.

문제는 웹 서비스 정의가 문자열 (사용자 이름)을 가져 왔지만 아무 것도 보내지 않는다는 것을 나타냅니다. 이 오류로 인해 웹 서비스가 호출되지 않습니다. 함수 인수가 작동하려면 모든 함수 인수에 대해 적절한 데이터 유형을 보내야합니다. null을 보내려는 경우 명시 적으로 지정하십시오. { userName: null }

+0

저는 이것을 .NET 담당자에게 맡겨야한다는 것을 알고있었습니다. jQuery 각도에서 벗어나려고 시도했지만 빠진 매개 변수를 놓쳤습니다. –

관련 문제