Jquery asp.net razor pages webmatrix ajax post赢得';行不通
所以我只是想用ajax将数据发布到页面上。。但是它不起作用。。有什么想法吗Jquery asp.net razor pages webmatrix ajax post赢得';行不通,jquery,asp.net,ajax,razor,webmatrix,Jquery,Asp.net,Ajax,Razor,Webmatrix,所以我只是想用ajax将数据发布到页面上。。但是它不起作用。。有什么想法吗 $.ajax({ url: '/REST/GetResponse.cshtml', type: "POST", dataType: "json", contentType: "application/json; charset=utf-8",
$.ajax({
url: '/REST/GetResponse.cshtml',
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
username: $('#username').val(),
firstname: $('#firstname').val(),
lastname: $('#lastname').val(),
email: $('#email').val(),
password1: $('#password1').val(),
password2: $('#password2').val(),
}),
success: function (result) {
alert("success " + result.UserName);
},
error: function (result) {
alert("Failed");
}
});
}
这是我的ajax帖子-
@{
if (IsPost)
{
var password = Request["password1"];
var username = Request["username"];
}
}
这是它被发布到的页面,但当我看到控制台时,它会说(取消),错误函数会弹出警报
感谢您的帮助:)谢谢ASP.Net网页通常希望
POST
请求以application/x-www-form-urlencoded
而不是JSON的形式发送。只需将contentType
设置为该值(或者根本不设置,因为这是默认值),然后去掉JSON.stringify()
调用。jQuery将自动为您进行编码。您的最佳选择是序列化表单并提交表单。如果您的表单id为“userdata”,那么您的Ajax帖子应该是:
$.ajax({
url: '/REST/GetResponse.cshtml',
type: "POST",
dataType: "text",
data: $("#userdata").serialize(),
success: function (result) {
alert("success " + result);
},
error: function () {
alert("Failed");
}
};
@{
string input;
using(var reader = new StreamReader(Request.InputStream)){
input = reader.ReadToEnd();
}
var user = Json.Decode(input);
var password = user.password1;
var username = user.username;
// and so on ...
try
{
// do something...
Response.Write(username);
}
catch (Exception ex)
{
Response.StatusCode = 500;
Response.Write(ex.Message);
}
}
您的/REST/GetResponse.cshtml文件如下:
@{
var password = Request["password1"];
var username = Request["username"];
// and so on ...
try
{
// do something...
Response.Write(username);
}
catch (Exception ex)
{
Response.StatusCode = 500;
Response.Write(ex.Message);
}
}
相反,如果您想保留原来的Ajax帖子,我认为/REST/GetResponse.cshtml应该是:
$.ajax({
url: '/REST/GetResponse.cshtml',
type: "POST",
dataType: "text",
data: $("#userdata").serialize(),
success: function (result) {
alert("success " + result);
},
error: function () {
alert("Failed");
}
};
@{
string input;
using(var reader = new StreamReader(Request.InputStream)){
input = reader.ReadToEnd();
}
var user = Json.Decode(input);
var password = user.password1;
var username = user.username;
// and so on ...
try
{
// do something...
Response.Write(username);
}
catch (Exception ex)
{
Response.StatusCode = 500;
Response.Write(ex.Message);
}
}
您似乎期望发布键/值对(
Request[“key”]
)与JSON.stringify(对象的字符串表示形式<代码>{“x”:5,“y”:6})