我使用以下代码调用ashx页面。但它不适合我。我把我的代码放在这里。我总是收到错误消息消息"请求失败"。请帮帮我..
<script type="text/javascript">
function CallLoginHandler(user, pass) {
alert(user);//Got value
alert(pass);//Got Value
$(function(){
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx?MainPage=GetUserDetails&Type=2&user=" + user + "&pass=" + pass + "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnComplete,
error: OnFail
});
return false;
});
}
function OnComplete(result) {
alert([result.Id, result.Name, result.Age, result.Department]);
}
function OnFail(result) {
alert('Request Failed');
}
</script>
答案 0 :(得分:1)
删除这些行:
$(function(){ // <----remove this
return false; // and this
}); // and this too
更新此功能:
function CallLoginHandler(user, pass) {
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx", // updated url
data: { // pass your data like this since type is post
MainPage:"GetUserDetails",
Type:2,
user:user,
pass:pass
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnComplete,
error: OnFail
});
}
并且您的网址也不正确:
url: "../handler/JQGridHandler...... + pass + "",
// --here you have a blank `""` after pass-----^
并且因为您的type: "post"
所以您可以传递这样的数据:
data: {
MainPage:"GetUserDetails",
Type:2,
user:user,
pass:pass
},
答案 1 :(得分:0)
将您的字符串分隔为要编码的javascript对象,并根据您的内容类型将其作为JSON发送到服务器。另外,在函数调用中删除$(function(){
,这里没用。
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx';
contentType: "application/json; charset=utf-8",
dataType: "json",
data: {
MainPage: 'GetUserDetails',
Type: 2,
user: user,
pass: pass
}
success: OnComplete,
error: OnFail
});
如果这不起作用,则问题可能是以下之一:
application/x-www-form-urlencoded
,但您已宣布为json
答案 2 :(得分:0)
注意:请勿发送您的用户并传入查询字符串。
function CallLoginHandler(user, pass) {
$.ajax({
type: "POST",
url: "../handler/JQGridHandler.ashx",
data: {
MainPage: 'GetUserDetails',
Type: 2,
user: user,
pass: pass
},
// DO NOT SET CONTENT TYPE to json
// contentType: "application/json; charset=utf-8",
// DataType needs to stay, otherwise the response object
// will be treated as a single string
dataType: "json",
success: OnComplete,
error: OnFail
});
}); }
您的handler.ashx文件
using System;
using System.Web;
using Newtonsoft.Json;
public class Handler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string user= context.Request.Form["user"];
//.....
var wrapper = new { d = myName };
// in order to use JsonConvert you have to download the
// Newtonsoft.Json dll from here http://json.codeplex.com/
context.Response.Write(JsonConvert.SerializeObject(wrapper));
}
public bool IsReusable
{
get
{
return false;
}
}
}