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

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

通过下面的 JavaScript 代码,我正在尝试一些 BackboneJs 概念。无法弄清楚为什么调用 XHR 请求后的响应是整页的 HTML,而不是 Person 类 的序列化版本。看看下面 服务器端代码为 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)
});

最佳答案

尝试设置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/

相关文章:

javascript - 在 KnockoutJS 的 View 中处理不存在的 observableArray 属性

javascript - 当模态在 w3.css 中滚动时如何隐藏文档垂直滚动条?

javascript - 将数组列表存储在变量中

javascript - jquery 禁用上一个下一个按钮模态图像

javascript - Enyo MVC实现和粒 subview 渲染

javascript - ES6 解构为 "this"

javascript - jQuery:加载图像子集后立即执行函数

javascript - 在 php 中使用 javascript 数组内容

mysql - Spring 存储库中的自定义查询

model-view-controller - 应用架构MVC,MVVM等