admin管理员组文章数量:1430534
I need to return an array of string from MyMethod at codebehind. But do I parse it on aspx page using javascript
?
[WebMethod]
public static string[] MyMethod(){
return new[] {"fdsf", "gfdgdfgf"};
}
..........
function myFunction() {
$.ajax({ ......
success: function (msg) {
//how do I parse msg?
}
});
};
I need to return an array of string from MyMethod at codebehind. But do I parse it on aspx page using javascript
?
[WebMethod]
public static string[] MyMethod(){
return new[] {"fdsf", "gfdgdfgf"};
}
..........
function myFunction() {
$.ajax({ ......
success: function (msg) {
//how do I parse msg?
}
});
};
Share
Improve this question
asked Jul 13, 2012 at 21:29
user266003user266003
3 Answers
Reset to default 3First, make sure you've tagged your class with [ScriptService]
to allow it to be called through AJAX. Something like:
[ScriptService] //<-- Important
public class WebService : System.Web.Services.WebService
{
[ScriptMethod] //<-- WebMethod is fine here too
public string[] MyMethod()
{
return new[] {"fdsf", "gfdgdfgf"};
}
}
You can then read the result with jQuery directly, as there's no need to parse anything:
$(document).ready(function() {
$.ajax({
type: "POST",
url: "WebService.asmx/MyMethod",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// msg.d will be your array with 2 strings
}
});
});
Another approach is to just include a reference to:
<script src="WebService.asmx/js" type="text/javascript"></script>
This will generate proxy classes to allow you to call web methods directly. For example:
WebService.MyMethod(onComplete, onError);
The onComplete
function will receive a single parameter with the results of the web service call, in your case a Javascript array with 2 strings. In my opinion, this is an easier solution than using jQuery and worrying about the URL and HTTP payload.
Use the jQuery iterator to iterate over the strings in the msg result like so.
function myFunction() {
$.ajax({ ......
success: function (msg) {
$.each(msg, function(index, value) {
alert(value);
});
}
});
};
The response object
will contain an object called d
which wraps the values returned from your WebMethod. Just access it like so:
function myFunction() {
$.ajax({ ......
success: function (msg) {
//how do I parse msg?
alert(msg.d); //alerts "fdsf", "gfdgdfgf"
}
});
};
See this question for an explanation.
本文标签: Aspnet WebMethodreturn string and parse it using JavaScriptStack Overflow
版权声明:本文标题:Asp.net WebMethod - return string[] and parse it using JavaScript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745478765a2660083.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论