我的页面上有2个ajax函数。单击网格内的链接时单击一个,单击按钮时单个链接。来自网格的那个完美无缺。但是,单击按钮的功能每次都会产生错误。
有人可以告诉我这里我出错了吗?我将不胜感激任何帮助。这是失败的:
function createSource() {
$.ajax({
type: "POST",
url: "Test.aspx/createSource",
data: '{"schoolID":"' + $('#ddSchools').val() + '","vendor":"' + $('#txtVendor').val() + '","tSource":"' + $('#txtTSource').val()+ '"}',
contentType: "application/json",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function (xhRequest, ErrorText, thrownError) {
alert(thrownError);
}
});
}
Web方法会有更多的代码,但无论如何我似乎无法打它。这是webmethod:
[WebMethod]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true)]
public static string createSource(int schoolId, string vendor, string tSource)
{
try
{
string status = "This is a test string!";
return status;
}
catch
{
throw new Exception("Could not create source code!");
}
}
另外,我如何才能获得导致此功能失败的确切错误?
提前感谢您的帮助!!
<input id="cmdSubmit_Create" value="Submit" type="submit" />
任何想法?
作为参考,我将把有效的代码放在document.ready:
上$(document).ready(function () {
$.ajax({
type: "POST",
url: "Test.aspx/createSource",
data: '{"schoolId":"2236","vendor":"test","tsource":"test1234"}',
contentType: "application/json",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("status: " + textStatus + " errorThrown: " + errorThrown);
},
complete: function (jqXHR, textStatus) {
alert("status: " + textStatus);
}
});
});
[WebMethod]
public static string helloWorld(string schoolId, string vendor,string tsource)
{
try
{
StringBuilder sb = new StringBuilder();
sb.Append("Hello World! " + schoolId + '-' + vendor + '-' + tsource);
return sb.ToString();
}
catch
{
throw new Exception("Could not create source code!");
}
}
如果我尝试在单击cmdSubmit_Create时调用相同的webmethod它不起作用:
$('#cmdSubmit_Create').click(function () {
$.ajax({
type: "POST",
url: "Test.aspx/helloWorld",
data: '{"schoolId":"2236","vendor":"test","tsource":"test1234"}',
contentType: "application/json",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function (xhr, status, error) {
alert('error' + error)
}
});
答案 0 :(得分:0)
您的服务需要GET
UseHttpGet = true 正如您所做的那样POST
尝试
type: "GET",
答案 1 :(得分:0)
使用以下代码
$('#cmdSubmit_Create').click(function () {
$.ajax({
type: "POST",
url: "Test.aspx/helloWorld",
data: '{"schoolId":"2236","vendor":"test","tsource":"test1234"}',
contentType: "application/json",
dataType: "json",
success: function (msg) {
alert(msg.d);
},
error: function (xhr, status, error) {
alert('error' + error)
}
});
return false;
});
http://cmsnsoftware.blogspot.com/2011/01/how-to-call-csharp-function-in-ajax.html