现在使用jQuery调用页面方法 - Backbone.Js

时间:2012-02-07 04:32:15

标签: javascript jquery model-view-controller backbone.js underscore.js

使用下面的javascript代码我正在尝试一些BackboneJs概念。无法弄清楚为什么调用XHR请求后的响应是整页HTML而不是Person class的序列化版本。看看下面 服务器端代码为C#ASP.NET 2.0

注意:忘记模型上的urlurlroot,我正在使用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)
});

2 个答案:

答案 0 :(得分:0)

尝试设置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)
});

答案 1 :(得分:0)

我不明白为什么但是jQuery让我按照这个奇怪的程序来完成这个。

将有效的json序列化为URL编码格式&amp;不是json字符串哪个错了。

$.ajaxSetup({
    contentType: "application/json; charset=utf-8"
});

Backbone.sync = function (met, mod, op) {
    console.log("method", met, "model", mod);
    switch (met) {
        case "create":
            $.post("index.aspx/CreatePerson", { "newPerson": mod.attributes }, function () { console.log(arguments) }, "json");
            break;
        case "update":
            var x = { "newPerson": mod.attributes };                
            x = JSON.stringify(x);                
            $.post("index.aspx/CreatePerson", x, function () { console.log(arguments) });
            break;
        case "delete":
            break;
        case "read":
            break;
        default:
            break;
    }
};