用jquery的ajax返回字符串,却出错 ?
js代码:
$(document).ready(function() {
$("#btn").click(function() {
alert(webs1( 'aa'));
});
});
function webs2(value1) {
var params = '{value1:"' + value1 + '"}';
$.ajax({
type: "POST",
url: "Default.aspx/getstr",
data: params,
dataType: "text",
contentType: "application/json; charset=utf-8",
beforeSend: function(XMLHttpRequest) {
//
},
success: function(msg) {
return "ok";
},
error: function(xhr, msg, e) { return "error"; }
});
}
.CS代码:
[System.Web.Services.WebMethod()]
public static string getStr(string value1)
{
return "str";
}
运行结果却显是“undefined”
------解决方案--------------------第一,函数名都搞错了,都怎么贴的代码,⊙﹏⊙b汗。。难道发帖还手动打一次代码?。。
alert(webs
1( 'aa'));
function webs
2
第二,楼主要搞清楚你的ajax是异步的,有时间差,而且你的回调函数中返回值没有,不是webs2的返回值,要改成同步的
function webs2(value1) {
var rst="";
var params = '{value1:"' + value1 + '"}';
$.ajax({
type: "POST",
url: "Default.aspx/getstr",
data: params,
async:false,
dataType: "text",
contentType: "application/json; charset=utf-8",
beforeSend: function(XMLHttpRequest) {
//
},
success: function(msg) {
rst= "ok";
},
error: function(xhr, msg, e) { return "error"; }
});
return rst
}