通过JS,数据类型的Json Web服务调用 [英] Web service call through JS, DataType Json
问题描述
我想通过调用一个JS的Web服务,但无论如何它没有得到调用。
我试图使2号总和。
I am trying to call web service through a JS but anyhow it doesnt get call. I am trying to make sum of 2 number.
页面包含3 文本框
,它已就文本设置硬codded
如
Page contains of 3 textbox
and it has it text set hard codded
as
:
<form id="form1" runat="server">
<div>
<asp:TextBox ID="Text1" Text="5" runat="server">
</asp:TextBox>
<asp:TextBox ID="Text2" Text="2" runat="server">
</asp:TextBox>
<asp:TextBox ID="Text3" runat="server">
</asp:TextBox>
</div>
</form>
我的code如下:
My code are as follows:
<script type="text/javascript">
$(document).ready(function () {
debugger;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "C:/Users/hp/Documents/visual studio 2010/Projects/WebApplication3/WebApplication3/WebService1.asmx/sum",
data: "{'a':'" + $('input[id$=Text1]').val() + "','b':'" + $('input[id$=Text2]').val() + "'}",
dataType: "json",
success: function (data) {
alert(data);
var results = eval('(' + data.d + ')');
if (results == "success") {
$('input[id$=Text3]').val(data);
//$('span[id$=lblErr]').hide();
}
else {
$('span[id$=lblmsg]').hide();
// $('span[id$=lblErr]').show();
}
},
error: function () {
alert('Error');
}
});
});
</script>
WebService的名称WebForm1.aspx的
WebService name WebForm1.aspx
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public string sum(string a, string b)
{
string json = "";
int sum = Convert.ToInt32(a) + Convert.ToInt32(b);
System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
json = oSerializer.Serialize(sum);
return json;
}
}
这显示出在每次运行时错误对话框。请帮助我通过它。谢谢你。
It showing Error box on each run. Kindly assist me through it. Thanks.
推荐答案
您的网址是错误的。它应该是这种形式的:</ p>
Your URL is wrong. It should be of this form:
url: "/WebService1.asmx/sum"
和,以确保它始终解析正确的道路,而是可以做到这一点:
And to make sure it always resolves to the right path, you can instead do this:
url: '<%=ResolveClientURL("~/WebService1.asmx/sum%>")'
另外,你的成功处理,你不需要做的:
Also, in your success handler, you don't need to do:
var results = eval('(' + data.d + ')');
您可以简单地做:
var result= data.d;
最后,在的WebMethod,不需要使用的JavaScriptSerializer在所有。你可以简单地做:
Finally, in your WebMethod, you don't need to use the JavascriptSerializer at all. You can simply do:
int sum = ...
return sum;
响应已经是JSON格式。无需序列两次。
The response is already in JSON format. No need to serialize it twice.
这篇关于通过JS,数据类型的Json Web服务调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!