3

我第一次使用backbone.js,我与php和mysql一起使用,这样我就可以使用主干从数据库发送和接收数据,但删除请求方法有问题。我无法访问与请求方法一起发送的数据,就像使用 post 和 put 一样。POST 和 PUT 在此脚本中完美运行,只是删除了我遇到的问题。

这是我的代码。

helloWorld.js

(function($) {

var Item = Backbone.Model.extend({
    url: 'http://mysite.com/syncItem.php', 
    defaults: {
        part1: 'hello',
        part2: 'world',
    }
});

var List = Backbone.Collection.extend({
    model: Item 
});

var ItemView = Backbone.View.extend({
    tagName: 'li', 
    events: {
        'click span.swap': 'swap', 
        'click span.delete': 'remove'
    },

    initialize: function() {
        _.bindAll(this, 'render', 'unrender', 'swap', 'remove'); 

        this.model.bind('change', this.render); 
        this.model.bind('remove', this.unrender);
    },

    render: function() {
        $(this.el).html('<span style="color:black;">' + this.model.get('part1') +' '+this.model.get('part2')+'</span> &nbsp; &nbsp; <span class="swap" style="font-family:sans-serif; color:blue; cursor:pointer;">[swap parts]</span> <span class="delete" style="cursor:pointer; color:red; font-family:sans-serif;">[delete]</span>');
        return this; 
    },

    unrender: function() {
        $(this.el).remove();
    },

    swap: function() {
        var swapped = {
            part1: this.model.get('part2'),
            part2: this.model.get('part1')  
        };
        this.model.set(swapped);
        this.model.sync("update", this.model);
    },

    remove: function() {
        this.model.sync("delete", this.model);  //deletes Item from server DB
        this.model.destroy(); //deletes Item from collection
    }
});

var ListView = Backbone.View.extend({
    el: $('div#backboneContainer'),  

    events: {
        'click button#add': 'addItem'   
    },

    initialize: function() {
        _.bindAll(this, 'render', 'addItem', 'appendItem');

        this.collection = new List(); 
        this.collection.bind('add', this.appendItem); 

        this.counter = 0;
        this.render();  
    },

    render: function() {
        var self = this;
        $(this.el).append("<button id='add'>Add List Item</button>");
        $(this.el).append("<ul></ul>");
    },

    addItem : function() {
        this.counter++;
        item = new Item({id: this.counter}); 
        item.set({
            part2: item.get('part2') + this.counter 
        });
        this.collection.add(item); 
        item.sync("create", item);
    },

    appendItem: function() {
        var itemView = new ItemView({
            model: item 
        });
        $('ul', this.el).append(itemView.render().el);
    }
});

var listView = new ListView();
})(jQuery);

同步项.php

<?php
include("includes/openDbConn.php");
$request_method = strtolower($_SERVER['REQUEST_METHOD']);
switch($request_method) {
    case 'post': {
        $data = json_decode(file_get_contents('php://input'));
        if($stmt = $mysqli->prepare("INSERT INTO backbonetest (modelId, part1, part2) VALUES (?, ?, ?)"))
        {
            $stmt->bind_param("iss", $data->{'id'}, $data->{'part1'}, $data->{'part2'});
            $stmt->execute();
        }
        break;  
    }
    case 'get': {
        //NOT FINISHED
        break;  
    }
    case 'put': {
        $data = json_decode(file_get_contents('php://input')); 
        if($stmt = $mysqli->prepare("UPDATE backbonetest SET part1 = ?, part2 = ? WHERE modelId = ?"))
        {
            $stmt->bind_param("ssi", $data->{'part1'}, $data->{'part2'}, $data->{'id'});
            $stmt->execute();
        }
        break;
    }
    case 'delete': {
        $data = json_decode(file_get_contents('php://input')); //gets data from the json that was sent with the request
        if($stmt = $mysqli->prepare("DELETE FROM backbonetest WHERE modelId = ?"))
        {
            $stmt->bind_param("i", $data->{'id'});
            $stmt->execute();
        } 
        break;  
    }
}
?>

我已将错误的范围缩小到两个位置:我调用的位置this.model.sync("delete", this.model);$data = json_decode(file_get_contents('php://input'));删除的情况。所以我想知道在处理删除请求方法时是否有一种特殊的方式来访问数据,或者我只是在主干中调用了删除函数错误?

4

2 回答 2

1

您有一个未实现期望的问题:) DELETEBackbone 中的请求默认情况下不发送属性为POSTPUT并且PATCH执行1:比较此 Fiddle http://jsfiddle.net/fz68a/model.save发送的请求和model.destroy

您可以覆盖Item.sync以赋予它您期望的行为:

var Item = Backbone.Model.extend({
    defaults: {
        part1: 'hello',
        part2: 'world'
    },

    sync: function (method, model, options) {
        if (method === 'delete') {
            options = options || {};
            options.contentType = 'application/json';
            options.data = JSON.stringify(this.toJSON());
        }

        return Backbone.sync.call(this, method, model, options);
    }
});

还有一个演示http://jsfiddle.net/fz68a/1/


1查看 Backbone 源代码http://documentcloud.github.io/backbone/docs/backbone.html#section-139

于 2013-09-14T08:35:26.337 回答
0

从我在你的 php 代码中看到的。应该已经这样做了。$_SERVER['REQUEST_METHOD'] 因为您已经在使用它已经回答了您的问题。您还可以转储 $_SERVER以查看 yuo 主干应用程序是否确实提出了请求。

另一个注意事项...

...   
 remove: function() {
        this.model.sync("delete", this.model);  //deletes Item from server DB
        this.model.destroy(); //deletes Item from collection
    }
...

您不需要调用model.sync,因为调用 destroy 已经隐式执行此操作。 http://backbonejs.org/#Model-destroy

...
 addItem : function() {
        this.counter++;
        item = new Item({id: this.counter}); 
        item.set({
            part2: item.get('part2') + this.counter 
        });
        this.collection.add(item); 
        item.sync("create", item);
    },
...

也不是做一个collection.add. 你可以调用collection.create
http://backbonejs.org/#Collection-create

于 2013-09-14T07:41:38.510 回答