gpt4 book ai didi

c# - JQuery ajax 调用 httpget webmethod (c#) 不工作

转载 作者:可可西里 更新时间:2023-11-01 08:03:04 25 4
gpt4 key购买 nike

我正在尝试让 ajax 访问代码隐藏的 web 方法。问题是我不断从 jQuery onfail 方法中收到错误“parserror”。

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

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>

代码隐藏

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

正在使用的 URL

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

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

任何帮助将不胜感激。

最佳答案

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

首先验证服务器端。

  1. 将 webmethods.aspx 重命名为 webmethods.asmx。
  2. 确认您放置在\内部并且配置中还存在用于 asmx 扩​​展的 httpHandlers (ScriptHandlerFactory):

    <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. 验证是否为从 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" ?>
<string xmlns="http://tempuri.org/">li1234</string>

您可以确定您的服务部件工作正常。

备注: 独立于“ResponseFormat = System.Web.Script.Services.ResponseFormat.Json”,如果“Content-Type:application/json;”,则服务响应带有 XML 响应未在请求中设置。

现在我们将修复客户端代码。我希望我放在以下代码中的注释能解释所有问题。

再多说一句。在代码的最后一部分,我调用了一个更“复杂”的网络方法:

[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 插件,如果有人喜欢,可以用 Crockford 的 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);
}
}
});

关于c# - JQuery ajax 调用 httpget webmethod (c#) 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2651091/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com