JQuery ajax 调用 httpget webmethod (c#) 不起作用 [英] JQuery ajax call to httpget webmethod (c#) not working

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

问题描述

我正在尝试通过 ajax 访问后台代码中的 webmethod.问题是我不断从 jQuery onfail 方法中收到错误parserror".

如果我将 GET 更改为 POST,一切正常.请看我下面的代码.

Ajax 调用

背后的代码

[System.Web.Services.WebMethod][System.Web.Script.Services.ScriptMethod(UseHttpGet = true,ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]公共静态字符串 AjaxGet(string id){返回标识;}

Web.config

 <协议><add name="HttpGet"/></协议></webServices>

正在使用的网址

<块引用>

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

作为响应的一部分,它返回页面 webmethods 的 html.

任何帮助将不胜感激.

解决方案

首先我要说的是,你选择的不是最简单的方法.ScriptMethods 很容易与 ASP.NET ScriptManager 一起使用,而不是与 jQuery 一起使用.我建议您最好使用支持 JSON 的 WCF HTTP 服务(最好是 RESTfull 服务),而不是您现在尝试使用的 ASMX Webservice.尽管如此,您还是可以在客户端不使用任何 Microsoft 技术的情况下编写代码.

首先验证服务器端.

  1. 将 webmethods.aspx 重命名为 webmethods.asmx.
  2. 验证您放置在 里面,并且配置中也存在 asmx 扩​​展 (ScriptHandlerFactory) 的 httpHandlers:

    <预><代码><配置><!-- ... --><system.web><网络服务><协议><add name="HttpGet"/></协议></webServices><httpHandlers><!-- ... --><add verb="*" path="*.asmx"type="System.Web.Script.Services.ScriptHandlerFactory"验证=假"/></httpHandlers></system.web></configuration>

  3. 验证为从 System.Web.Services.WebService 继承的类设置的 [ScriptService] 属性([System.Web.Script.Services.ScriptService],如果您喜欢全名).

    莉>

现在您可以测试该服务.在您的 Web 浏览器 URL 中打开,例如 http://localhost/webmethods.asmx/AjaxGet?id=li1234如果你收到类似
的东西<?xml version="1.0" encoding="utf-8" ?>
li1234

您可以确定您的维修部件工作正常.

备注:独立于ResponseFormat = System.Web.Script.Services.ResponseFormat.Json"的属性,如果Content-Type:application/json;"未在请求中设置.

现在我们将修复客户端代码.我希望我在以下代码中放置的注释可以解释所有内容.

再补充一句.在代码的最后一部分,我调用了一个更复杂"的网络方法:

[WebMethod][ScriptMethod (UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]公共输出数据 AjaxGetMore(输入数据输入){返回新的输出数据(){id = input.id,message = "它的工作!",myInt = input.myInt+1};}

哪里

public class OutputData {公共字符串 ID { 获取;放;}公共字符串消息 { 获取;放;}公共 int myInt { 得到;放;}}公共类输入数据{公共字符串 ID { 获取;放;}公共 int myInt { 得到;放;}}

现在只有 JavaScript 代码在某些地方使用 JSON 插件,如果有人喜欢,可以用 Crockford 的 json2.js 替换.

var id = "li1234";//版本 1 - 有效var idAsJson = '"' + id + '"';//字符串以 JSON 格式序列化$.ajax({类型:获取",url: "/webmethods.asmx/AjaxGet?id=" + idAsJson,contentType: "application/json; charset=utf-8",成功:功能(味精){警报(msg.d);//var msg = {d: "li1234"}},错误:功能(资源,状态){如果(状态===错误"){//errorMessage 可以是具有 3 个字符串属性的对象:ExceptionType、Message 和 StackTracevar errorMessage = $.parseJSON(res.responseText);警报(错误消息.消息);}}});//关于 JSON 插件的第 2 版$.ajax({类型:获取",url: "/webmethods.asmx/AjaxGet?id=" + $.toJSON(id),contentType: "application/json; charset=utf-8",成功:功能(味精){警报(msg.d);//var msg = {d: "li1234"}},错误:功能(资源,状态){如果(状态===错误"){//errorMessage 可以是具有 3 个字符串属性的对象:ExceptionType、Message 和 StackTracevar errorMessage = $.parseJSON(res.responseText);警报(错误消息.消息);}}});//jQuery 将为我们构造 URL 的版本 3$.ajax({类型:获取",url: "/webmethods.asmx/AjaxGet",数据:{id: $.toJSON(id)},数据类型:json",contentType: "application/json; charset=utf-8",成功:功能(味精){警报(msg.d);//var msg = {d: "li1234"}},错误:功能(资源,状态){如果(状态===错误"){//errorMessage 可以是具有 3 个字符串属性的对象:ExceptionType、Message 和 StackTracevar errorMessage = $.parseJSON(res.responseText);警报(错误消息.消息);}}});//版本 4.我们为我们的数据设置了Content-Type: application/json",但我们不使用//不是 'dataType: "json"' 参数.然后我们在请求中有Accept: */*"//而不是之前的Accept: application/json, text/javascript, */*".//一切都像以前一样正常.$.ajax({类型:获取",url: "/webmethods.asmx/AjaxGet",数据:{id: $.toJSON(id)},contentType: "application/json; charset=utf-8",成功:功能(味精){警报(msg.d);//var msg = {d: "li1234"}},错误:功能(资源,状态){如果(状态===错误"){//errorMessage 可以是具有 3 个字符串属性的对象:ExceptionType、Message 和 StackTracevar errorMessage = $.parseJSON(res.responseText);警报(错误消息.消息);}}});//版本 5.如果我们不在我们的请求中放置Content-Type: application/json",我们//接收带有HTTP/1.1 200 OK"标头的 XML (!!!) 响应//"Content-Type: text/xml; charset=utf-8" 将被放置.//如何读入//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 不会使响应数据的 JSON 序列化//安全原因.$.ajax({类型:获取",url: "/webmethods.asmx/AjaxGet",数据:{id: $.toJSON(id)},数据类型:json",//contentType: "application/json; charset=utf-8",成功:功能(味精){警报(msg.d);//var msg = {d: "li1234"}},错误:功能(资源,状态,前){//由于解析服务器响应时出错,这里的代码将起作用if (res.status !== 200) {//如果不正常//我们在下一行收到异常,是var errorMessage = $.parseJSON(res.responseText);警报(错误消息.消息);} 别的 {alert("status=" + status + "
ex=" + ex + "
res.status=" + res.status + "
res.statusText=" + res.statusText +"
res.responseText=" + res.responseText);}}});//版本 6. 向/从服务发送更多 komplex 数据var myData = { id: "li1234", myInt: 100}$.ajax({类型:获取",url: "/webmethods.asmx/AjaxGetMore",数据:{输入:$.toJSON(myData)},数据类型:json",contentType: "application/json; charset=utf-8",成功:功能(味精){//var msg = {__type: "Testportal.OutputData", id: "li1234", message: "成功了!", myInt:101}alert("message=" + msg.d.message + ", id=" + msg.d.id + ", myInt=" + msg.d.myInt);},错误:功能(资源,状态){如果(状态===错误"){//errorMessage 可以是具有 3 个字符串属性的对象:ExceptionType、Message 和 StackTracevar errorMessage = $.parseJSON(res.responseText);警报(错误消息.消息);}}});

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.

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

Ajax Call

<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 Behind

[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>

The URL being used

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

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

Any help will be greatly appreciated.

解决方案

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. 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>
    

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

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.

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.

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

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

Where

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

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 + "
ex=" + ex + "
res.status=" + res.status + "
res.statusText=" + res.statusText +
                    "
res.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 调用 httpget webmethod (c#) 不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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