JQuery的AJAX调用的WebMethod HTTPGET(C#)不工作 [英] JQuery ajax call to httpget webmethod (c#) not working

查看:282
本文介绍了JQuery的AJAX调用的WebMethod HTTPGET(C#)不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得一个ajax获取到code后面一个WebMethod。问题是我一直从jQuery onfail 方法。

I am trying to get an ajax get to a webmethod in code behind. The problem is I keep getting the error "parserror" from the jQuery onfail method.

如果我改变得到一个POST一切工作正常。请参考下面我的code。

If I change the GET to a POST everything works fine. Please see my code below.

Ajax调用

<script type="text/javascript">
        var id = "li1234";

        function AjaxGet() {
            $.ajax({
                type: "GET",
                url: "webmethods.aspx/AjaxGet",
                data: "{ 'id' : '" + id + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: false,
                success: function(msg) {
                    alert("success");

                },
                error: function(msg, text) {
                    alert(text);
                }
            });
        }

    </script>

code背后

[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true,
    ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)] 
public static string AjaxGet(string id)
{
    return id;
}

的Web.config

        <webServices>
            <protocols>
                <add name="HttpGet"/>
            </protocols>
        </webServices>

正在使用的网址

........ / webmethods.aspx / AjaxGet {%20%27id%27%20:%20%27li1234%27}?

......../webmethods.aspx/AjaxGet?{%20%27id%27%20:%20%27li1234%27}

作为应对措施的一部分它返回的页面的webMethods的HTML。

As part of the response it is returning the html for the page webmethods.

任何帮助将大大AP preciated。

Any help will be greatly appreciated.

推荐答案

所有之前我可以说,你没有选择最简单的方式。 ScriptMethods很容易与jQuery与ASP.NET的ScriptManager并且不使用。我会建议你更好地使用JSON启用,WCF HTTP服务(如REST风格服务更好),而不是ASMX Webservice的,你现在尝试使用。
然而,我们可以让你code,而不使用在客户端的微软技术方面的工作。

Before all I could say, that you choose not the easiest way. ScriptMethods is easy to use together with ASP.NET ScriptManager and not with jQuery. I’ll recommend you better use JSON-enabled WCF HTTP Services (better as RESTfull Service) instead of ASMX Webservice which you try to use now. Nevertheless, one can makes you code working without using any Microsoft technologies on the client side.

所有验证服务器端的第一。

First of all verify Server side.


  1. 重命名webmethods.aspx到webmethods.asmx。

  2. 确认您放置\\内部和HttpHandlers的为ASMX扩展(ScriptHandlerFactory)也存在于配置:

  1. Rename webmethods.aspx to webmethods.asmx.
  2. Verify that you placed Inside of \ and a httpHandlers for asmx extension (ScriptHandlerFactory) also exist in the config:

<configuration>
  <!-- ... -->
  <system.web>
    <webServices>
      <protocols>
        <add name="HttpGet"/>
      </protocols>
    </webServices>
    <httpHandlers>
      <!-- ... -->
      <add verb="*" path="*.asmx"
           type="System.Web.Script.Services.ScriptHandlerFactory"
           validate="false"/>
    </httpHandlers></system.web></configuration>


  • 验证[ScriptService]属性([System.Web.Script.Services.ScriptService]如果你喜欢全名),请从System.Web.Services.WebService继承类设置。

  • Verify that [ScriptService] attribute ([System.Web.Script.Services.ScriptService] if you like full names) set for your class inherited from System.Web.Services.WebService.

    现在,你可以测试服务。打开你的Web浏览器的URL像<一个href=\"http://localhost/webmethods.asmx/AjaxGet?id=li1234\">http://localhost/webmethods.asmx/AjaxGet?id=li1234
    如果你收到回类似

    &LT;?XML版本=1.0编码=UTF-8&GT;

    &LT;字符串的xmlns =htt​​p://tempuri.org/&GT; li1234&LT; /串&GT;

    Now you could test the service. Open in you Web-Browser URL like http://localhost/webmethods.asmx/AjaxGet?id=li1234 If you receive back something like
    <?xml version="1.0" encoding="utf-8" ?>
    <string xmlns="http://tempuri.org/">li1234</string>

    您可以确信您服务的一部分工作正常。

    You can be sure that you service part works fine.

    注:独立工作的ResponseFormat = System.Web.Script.Services.ResponseFormat.Json属性的服务与答案XML响应,如果内容类型:应用程序/ JSON的;不设置该请求。

    Remark: Independ on "ResponseFormat = System.Web.Script.Services.ResponseFormat.Json" attribute the service answer with XML responses if "Content-Type:application/json;" not set in the request.

    现在,我们会解决客户code。我希望这是我放在以下code注释说明一切。

    Now we’ll fix the client code. I hope that comments which I placed in the following code explain all.

    还有一个小的话。在code最后一部分,我叫多了一个复杂的Web方法:

    One more small remark. In the last part of code I call one more "complex" web method:

    [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 code这在一些地方JSON插件,它可以与克罗克福德的json2.js被替换使用,如果有人preFER它。

    Now only JavaScript code which use in some places JSON plugin, which could be replaced with Crockford's json2.js, if somebody prefer it.

    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);
            }
        }
    });
    

    这篇关于JQuery的AJAX调用的WebMethod HTTPGET(C#)不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆