如何使用XMLHttpRequest直接调用我自己的服务器端函数。
假设我的aspx文件中有一个静态web方法,那么我如何通过XMLHttpRequest调用它。我需要传递给asp.net引擎的头信息,因此asp.net引擎可以调用我的方法并在后续流中返回响应。
这样我需要调用我的服务器端方法
<script type="text/javascript">
var request;
// A
// Here is the new function that is called when the user submits the form.
// This example uses POST.
function submitCallback() {
var inputValue = document.getElementById("SearchInput").value;
var sendStr = "name=" + inputValue;
request = new XMLHttpRequest();
// B
// Specify the POST method and send it.
request.open("POST", "Default.aspx/Getdata");
request.onreadystatechange = readyCallback;
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.setRequestHeader("IsLookup", "true");
request.send(sendStr);
}
</script>
请指导我....谢谢
答案 0 :(得分:2)
我相信当你在我的aspx文件中说一个静态web方法时,你可能会引用ASP.NET页面方法。 ASP.NET页面方法(或JS中使用的Web服务)对i / p和o / p使用JSON序列化。因此,您需要将JSON设置为请求的内容类型,并实际在主体中发送JSON字符串,即
。...
var sendStr = "{name:" + inputValue + "}";
...
request.setRequestHeader("Content-Type", "application/json");
...
request.send(sendStr);
此外,我建议您使用jquery或ASP.NET生成的代理(通过ScriptManager),而不是直接对XmlHttpRequest进行编码。有关如何使用jquery调用Page方法,请参阅此article。
答案 1 :(得分:0)
我认为,最简单的方法是使用jQuery进行ajax请求:http://api.jquery.com/category/ajax/