通过下面的 JavaScript 代码,我正在尝试一些 BackboneJs 概念。无法弄清楚为什么调用 XHR 请求后的响应是整页的 HTML,而不是 Person 类
的序列化版本。看看下面
服务器端代码为 C#
和 ASP.NET 2.0
注意:忘记模型上的url
和urlroot
,我正在使用backbonejs Sync
Javascript
window.Person = Backbone.Model.extend({
defaults: {
id: Math.random(),
name: "Type your name"
},
initialize: function (model) {
this.bind("change", this.ModelChanged);
},
ModelChanged: function () {
},
url: "CreatePerson",
urlRoot: "/index.aspx/"
});
Backbone.sync = function (met, mod, op) {
switch (met) {
case "create":
break;
case "update":
break;
case "delete":
break;
case "read":
break;
default:
break;
}
};
服务器端代码
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static Person CreatePerson(Person newPerson)
{
List<Person> peopleList = HttpContext.Current.Session["People"] as List<Person>;
if (peopleList == null)
{
peopleList = new List<Person>();
}
Person p1 = new Person();
p1 = newPerson;
peopleList.Add(p1);
HttpContext.Current.Session["People"] = peopleList;
return p1;
}
人员类别
public class Person
{
public string Id
{
get;
set;
}
public string Name
{
get;
set;
}
}
最后是测试代码
var x = new Person({
name: "StackOverflow"
});
$.post("index.aspx/CreatePerson", "{" + JSON.stringify(x) + "}", function () {
console.log(arguments)
});
最佳答案
尝试设置contentType
$.ajaxSetup({
contentType: "application/json; charset=utf-8"
});
之后您的请求
var x = new Person({
name: "StackOverflow"
});
$.post("index.aspx/CreatePerson", "{" + JSON.stringify(x) + "}", function () {
console.log(arguments)
});
关于javascript - 现在使用 jQuery - Backbone.Js 调用页面方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9171041/