Как запустить JQuery Использовать HttpHandler - PullRequest
2 голосов
/ 01 ноября 2011

Это мой код. Default.aspx:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org
/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
Inherits="Sample001.Default" %>
<script src="jquery-1.6.4.min.js" type="text/javascript"></script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table>
            <tr>
                <td>
                    <asp:Label ID="lbl1" runat="server" />
                </td>
            </tr>
            <tr>
                <td>
                <asp:Label ID="masterlbl" Text="Master" runat="server" />
                </td>
                <td>
                    <span class="Mastercs">
                    <asp:DropDownList ID="ddl1" runat="server"/>
                    </span>
                </td>
                <td>
                <asp:Label ID="slavelbl" Text="Slave" runat="server" />
                </td>
                <td>
                    <span class="slavecs">
                    <asp:DropDownList ID="ddl2" runat="server"     />
                    </span>
                </td>
            </tr>
        </table>
    </div>
    </form>
    <script type="text/javascript">
        $(document).ready(function () {
            $('span.Mastercs select').change(function () {
                $.ajax({
                    type: "POST",
        url: "http://localhost/Sample001/Default.aspx/MyMethod",
                    data: "{}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (msg) {
                        $('#lbl1').text = msg;
                    }
                });
            });
        });
    </script>
</body>
</html>

Это Web.Config:

<?xml version="1.0"?>
<configuration>
    <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
        <handlers>
                <add name="MyMethod" verb="*" path="*.assq" 
    type="Sample001.MyHandler,Sample001" preCondition="integratedMode" />
        </handlers>
    </system.webServer>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
</configuration>

И обработчик:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Sample001 {
    public class MyHandler : IHttpHandler {
        public bool IsReusable {
            get { return true; }
        }
        public void ProcessRequest(HttpContext context) {
        context.Response.Write("Yeeeeeeeeeeeeeee Like it");
        }
    }
}

Я не могу правильно настроить IIS 7.0, как сказал 15Seconds , просто мог бы добавить свое собственное расширение (.assq) так:

enter image description here

При загрузке страницы и изменении выберите сценарий не работает enter image description here

А это мой ответ: Неизвестный веб-метод MyMethod.
Имя параметра: methodName body {font-family: "Verdana"; font-weight: normal; font-size: .7em; цвет: черный;} p {font-family: "Verdana"; font-weight: normal; цвет: черный; margin-top: -5px} b {font-family: "Verdana"; font-weight: bold; цвет: black; margin-top: -5px} H1 {font-family: "Verdana"; font-weight: normal; размер шрифта: 18pt; цвет: красный} H2 {font-family: "Verdana"; font-weight: normal; font- размер: 14pt; цвет: бордовый} pre {font-family: "Lucida Console"; размер шрифта: .9em} .marker {font-weight: bold; цвет: черный; текстовое оформление: нет;} .version {цвет: серый;} .error {margin-bottom: 10px;} .expandable {text-художественное оформление: подчеркивание; начертание шрифта: жирный; Цвет: темно-синий; Курсор: рука; }

<code>        <span><H1>Server Error in '/Sample001' Application.<hr width=100% size=1 
color=silver></H1>

        <h2> <i>Unknown web method MyMethod.<br>Parameter name: methodName</i>  
</h2></span>

        <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">

        <b> Description: </b>An unhandled exception occurred during the execution of 
the current web request. Please review the stack trace for more information about the 
error and where it originated in the code.

        <br><br>

        <b> Exception Details: </b>System.ArgumentException: Unknown web method 
MyMethod.<br>Parameter name: methodName<br><br>

        <b>Source Error:</b> <br><br>

        <table width=100% bgcolor="#ffffcc">
           <tr>
              <td>
                  <code>

An unhandled exception was generated during the execution of the current web request. 
Information regarding the origin and location of the exception can be identified using 
the exception stack trace below.</code>

              </td>
           </tr>
        </table>

        <br>

        <b>Stack Trace:</b> <br><br>

        <table width=100% bgcolor="#ffffcc">
           <tr>
              <td>
                  <code><pre>

[ArgumentException: Unknown web method MyMethod.
Parameter name: methodName]
System.Web.Handlers.ScriptModule.OnPostAcquireRequestState(Object sender, EventArgs  
eventArgs) +897827
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() 
+80
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean&amp; 
completedSynchronously) +270


Информация о версии: Microsoft .NET Framework Версия: 4.0.30319; ASP.NET версия: 4.0.30319.237 <! - [ArgumentException]: неизвестный веб-метод MyMethod. Имя параметра: methodName в System.Web.Handlers.ScriptModule.OnPostAcquireRequestState (Отправитель объекта, EventArgs eventArgs) в System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep .Execute () на System.Web.HttpApplication.ExecuteStep (шаг IExecutionStep, логическое & completedSynchronously) ->

почему этот код не работает? Почему в ответе говорится: неизвестный веб-метод MyMethod.? это из-за конфигурации IIS 7.0 или другой вещи?

KBoek помогите найти в чем проблема: основной из них: это 3 элемента вызывают путаницу jQuery:

данные: "{}", contentType: "application / json; charset = utf-8", dataType: "json",

и я его удаляю.

Ответы [ 3 ]

1 голос
/ 01 ноября 2011

Я бы лучше использовал следующую настройку:

Позвоните по следующему URL из JavaScript:

"http://localhost/Sample001/MyMethod.assq"
Затем зарегистрируйте этот URL в web.config
<add name="MyMethod" verb="*" path="MyMethod.assq" type="Sample001.MyHandler,Sample001" preCondition="integratedMode" />
Вам не нужно регистрироваться * .assqкак тип MIME в IIS.

Кстати, ни ваш JavaScript, ни ваш код C # не предоставляют никаких данных в формате JSON.Вам это не нужно, если вы просто хотите вернуть строку с сервера.Но, конечно, JSON - это хороший способ вернуть клиенту полный объект.

Альтернативы для определения "lbl1" из Javascript

<asp:Label ID="lbl1" runat="server" CssClass="myLabel" />

<script type="text/javascript">
  var label = $('.myLabel');
</script>
<span ID="lbl1">

<script type="text/javascript">
  var label = $('#lbl1');
</script>
0 голосов
/ 01 ноября 2011

Проблема в том, что в коде java-скрипта вы не запрашиваете свой обработчик http, а скорее вызываете Default.aspx.Проверьте следующую строку:

url: "http://localhost/Sample001/Default.aspx/MyMethod",

измените его (чтобы вызывался ваш обработчик) - например,

url: "http://localhost/Sample001/xyz.assq/MyMethod",

В зависимости от конфигурации вы можете использовать любое имя файла с расширениемassq и это должно сработать.Информация о пути ('/ MyMethod') также не нужна.

В дополнение к этому вам не нужно возиться с типами IIS MIME - это применимо только для статических файлов.

Кроме того, оригинальный синтаксис URL, который вы использовали, обычно используется для вызова методов страницы - см. эту статью , если вы этого хотите достичь.

0 голосов
/ 01 ноября 2011
$(document).ready(function () {
        $('span.Mastercs select').change(function () {
            $.ajax({
                type: "POST",
                url: "http://localhost/Sample001/MyMethod.assq",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {
                    $('#lbl1').text = msg;
                }
            });
        });
    });
...