我使用ajax来调用服务器端功能。由于某种原因,成功是触发但它没有达到该功能 这是javascript
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: "Server.aspx/sendEmail",
data: { name: "foo", company: "bar", country: "foo", email: "bar", msg: "bla" },
async: false,
success: function (data) {
var a = 3;
},
error: function (a, b) {
alert("error");
var a = 43;
}
});
});
这是c#
[WebMethod]
public static string sendEmail(string name, string company, string country, string email, string msg)
{
//somecode here
}
数据信息(由于某种原因它正在破坏)
<form method="post" action="./sendEmail?%7b%22name%22%3a%22foo%22%2c%22company%22%3a%22bar%22%2c%22country%22%3a%22foo%22%2c%22email%22%3a%22bar%22%2c%22msg%22%3a%22bla%22%7d" id="form1">
<div>
</div>
<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="368A1591" />
答案 0 :(得分:2)
在调用ASP.NET AJAX页面方法时,请考虑以下几点:
要使用ASP.NET AJAX page methods,您需要发出POST请求。这是为了防止CSRF
确保contentType
设置为application/json
。
JSON.stringify
将JavaScript对象转换为JSON文本。您的JS代码可能与此类似:
$(document).ready(function () {
var data = { name: "foo", company: "bar", country: "foo", email: "bar", msg: "bla" };
$.ajax({
url: "Server.aspx/sendEmail",
type: "POST",
data: JSON.stringify(data),
async: false,
contentType: 'application/json',
success: function (data) {
//Do something
},
error: function (xhr) {
alert('Request Status: ' + xhr.status
+ ' Status Text: ' + xhr.statusText
+ ' ' + xhr.responseText);
}
});
});
如果仍然无效,请检查statusText
是否有错误。