JQuery AJAX вызов веб-метода httpget (c #) не работает

Вы можете настроить максимальную длину для json-запросов в файле web.config:


    
        
            
                
                
            
        
    

Значение по умолчанию для maxJsonLength равно 102400. Дополнительные сведения см. на этой странице MSDN: http : //msdn.microsoft.com/en-us/library/bb763183.aspx

13
задан mauris 1 June 2011 в 02:08
поделиться

2 ответа

Прежде всего я могу сказать, что вы выбираете не самый простой путь. ScriptMethods легко использовать вместе с ASP.NET ScriptManager, а не с jQuery. Я рекомендую вам лучше использовать службы WCF HTTP с поддержкой JSON (лучше как RESTfull Service) вместо веб-службы ASMX, которую вы пытаетесь использовать сейчас. Тем не менее, можно заставить код работать без использования каких-либо технологий Microsoft на стороне клиента.

Прежде всего проверьте сторону сервера.

  1. Переименуйте webmethods.aspx в webmethods.asmx.
  2. Убедитесь, что вы разместили внутри \ и httpHandlers для расширения asmx (ScriptHandlerFactory) также существуют в конфигурации:

      
      {{1} }  
      
      
      
      
      
      
      
      
        
     
  3. Убедитесь, что атрибут [ScriptService] ([System.Web.Script.Services.ScriptService], если вам нужны полные имена) установлен для вашего класса, унаследованного от System.Web.Services.WebService.

Теперь вы можете протестировать службу. Откройте в своем браузере URL-адрес, например http: //localhost/webmethods.asmx/AjaxGet? Id = li1234 Если вы получите в ответ что-то вроде

li1234

Вы можете быть уверены, что ваша служебная часть работает нормально.

Примечание: Независимо от атрибута« ResponseFormat = System.Web.Script.Services.ResponseFormat.Json »атрибут ответ службы с ответами XML, если «Content-Type: application / json;» не задано в запросе.

Теперь мы исправим код клиента. Надеюсь, что комментарии, которые я разместил в следующем коде, все объясняют.

Еще одно небольшое замечание. В последней части кода я называю еще одно «Сложный» веб-метод:

[WebMethod]
[ScriptMethod (UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public OutputData AjaxGetMore (InputData input) {
    return new OutputData () {
        id = input.id,
        message = "it's work!",
        myInt = input.myInt+1
    };
}

Где

public class OutputData {
    public string id { get; set; }
    public string message { get; set; }
    public int myInt { get; set; }
}
public class InputData {
    public string id { get; set; }
    public int myInt { get; set; }
}

Теперь только код JavaScript, который в некоторых местах использует подключаемый модуль JSON, который можно заменить на json2.js Крокфорда, если кто-то предпочитает его.

var id = "li1234";
// version 1 - works
var idAsJson = '"' + id + '"';  // string serializes in JSON format
$.ajax({
    type: "GET",
    url: "/webmethods.asmx/AjaxGet?id=" + idAsJson,
    contentType: "application/json; charset=utf-8",
    success: function(msg) {
        alert(msg.d);   // var msg = {d: "li1234"} 
    },
    error: function(res, status) {
        if (status ==="error") {
            // errorMessage can be an object with 3 string properties: ExceptionType, Message and StackTrace
            var errorMessage = $.parseJSON(res.responseText);
            alert(errorMessage.Message);
        }
    }
});

// version 2 with respect of JSON plugin
$.ajax({
    type: "GET",
    url: "/webmethods.asmx/AjaxGet?id=" + $.toJSON(id),
    contentType: "application/json; charset=utf-8",
    success: function(msg) {
        alert(msg.d);   // var msg = {d: "li1234"} 
    },
    error: function(res, status) {
        if (status ==="error") {
            // errorMessage can be an object with 3 string properties: ExceptionType, Message and StackTrace
            var errorMessage = $.parseJSON(res.responseText);
            alert(errorMessage.Message);
        }
    }
});
// version 3 where jQuery will construct URL for us
$.ajax({
    type: "GET",
    url: "/webmethods.asmx/AjaxGet",
    data: {id: $.toJSON(id)},
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function(msg) {
        alert(msg.d);   // var msg = {d: "li1234"} 
    },
    error: function(res, status) {
        if (status ==="error") {
            // errorMessage can be an object with 3 string properties: ExceptionType, Message and StackTrace
            var errorMessage = $.parseJSON(res.responseText);
            alert(errorMessage.Message);
        }
    }
});
// version 4. We set "Content-Type: application/json" about our data, but we use no 
//            not 'dataType: "json"' parameter. Then we have "Accept: */*" in the request
//            instead of "Accept: application/json, text/javascript, */*" before.
//            Everithing work OK like before.
$.ajax({
    type: "GET",
    url: "/webmethods.asmx/AjaxGet",
    data: {id: $.toJSON(id)},
    contentType: "application/json; charset=utf-8",
    success: function(msg) {
        alert(msg.d);   // var msg = {d: "li1234"} 
    },
    error: function(res, status) {
        if (status ==="error") {
            // errorMessage can be an object with 3 string properties: ExceptionType, Message and StackTrace
            var errorMessage = $.parseJSON(res.responseText);
            alert(errorMessage.Message);
        }
    }
});
// version 5. If we don't place "Content-Type: application/json" in our reqest we
//            receive back XML (!!!) response with "HTTP/1.1 200 OK" header and 
//            "Content-Type: text/xml; charset=utf-8" which will be placed.
//            How one can read in
// http://weblogs.asp.net/scottgu/archive/2007/04/04/json-hijacking-and-how-asp-net-ajax-1-0-mitigates-these-attacks.aspx),
//             ASP.NET AJAX will not make JSON serialized of response data for
//             security reasons.
$.ajax({
    type: "GET",
    url: "/webmethods.asmx/AjaxGet",
    data: {id: $.toJSON(id)},
    dataType: "json",
    //contentType: "application/json; charset=utf-8",
    success: function(msg) {
        alert(msg.d);   // var msg = {d: "li1234"} 
    },
    error: function (res, status, ex) {
        // the code here will be works because of error in parsing server response
        if (res.status !== 200) {   // if not OK
            // we receive exception in the next line, be
            var errorMessage = $.parseJSON(res.responseText);
            alert(errorMessage.Message);
        } else {
            alert("status=" + status + "\nex=" + ex + "\nres.status=" + res.status + "\nres.statusText=" + res.statusText +
                    "\nres.responseText=" + res.responseText);
        }
    }
});
// version 6. Send more komplex data to/from the service
var myData = { id: "li1234", myInt: 100}
$.ajax({
    type: "GET",
    url: "/webmethods.asmx/AjaxGetMore",
    data: {input:$.toJSON(myData)},
    dataType: "json",
    contentType: "application/json; charset=utf-8",
    success: function(msg) {
        // var msg = {__type: "Testportal.OutputData", id: "li1234", message: "it's work!", myInt:101}
        alert("message=" + msg.d.message + ", id=" + msg.d.id + ", myInt=" + msg.d.myInt); 
    },
    error: function(res, status) {
        if (status ==="error") {
            // errorMessage can be an object with 3 string properties: ExceptionType, Message and StackTrace
            var errorMessage = $.parseJSON(res.responseText);
            alert(errorMessage.Message);
        }
    }
});
23
ответ дан 1 December 2019 в 20:28
поделиться
//...
data: { "id" : id },
//...

Данные - это объект, а не строка, которая выглядит как объект.

Если вы используете строку, это должна быть строка запроса URL в правильном формате, например:

//...
data: "id=" + encodeURIComponent(id) + "&otherstuff=" + encodeURIComponent(data),
//...
2
ответ дан 1 December 2019 в 20:28
поделиться
Другие вопросы по тегам:

Похожие вопросы: