【问题标题】:Backbone: passing data to server (save() method, php file)Backbone:将数据传递给服务器(save() 方法,php 文件)
【发布时间】:2014-01-18 17:49:59
【问题描述】:

希望你能帮我解决这个问题。

我想使用 Backbone 的 save() 方法并传递给 php 文件数据。 但是一开始我就有问题。

在浏览器的控制台中我执行:

var test = new MyModel(); //  - it's ok
test.toJSON(); // - it's ok
test.save(); // and here I have error "TypeError: d.collection is undefined"

当我使用 localStorage 时,everythink 都可以(我在下面的代码中对此进行了注释)。我可以创建模型、集合、视图等并对它们进行操作。

我尝试使用这些教程 net.tutsplus.com/tutorials/javascript-ajax/understanding-backbone-js-and-the-server/ 和 http://coenraets.org/blog/2011/12/restful-services-with-jquery-php-and-the-slim-framework/ 但我不知道 REST 是如何工作的以及我在哪里制作的错误。希望你能解释一下。

index.html

<!DOCTYPE html>
<html>
<head>
  <title>S.O.S</title>
</head>
<body>
<h1>Test</h1>
  <script src="jquery.min.js"></script>
  <script src="underscore-min.js"></script>
  <script src="backbone-min.js"></script>
  <script src="backbone.localStorage-min.js" type="text/javascript"></script>  

<script >

  window.MyModel = Backbone.Model.extend({
    defaults: {
      title: 'Test'
    },

    //localStorage: new Store('TEST')
    urlRoot: 'api/items'
  });


</script>

</body>
</html>

index.php

<?php
require 'Slim/Slim.php';
$app = new Slim();
$app->post('/items', 'addItem');
$app->run();


function addItem() {
    $request = Slim::getInstance()->request();
    try {
        echo json_encode('OK message'); 
    } catch(PDOException $e) {
        echo 'Error message'; 
    }
}
?>

文件夹结构

|->main_folder
           |-index.html
           |->api
                |->index.html
                |->Slim
                    |-> (folder with Slim php library)

【问题讨论】:

    标签: javascript php ajax rest backbone.js


    【解决方案1】:

    这是一个工作示例http://jsfiddle.net/acDb3/ 即使没有工作 REST,我也没有遇到您遇到的错误。 我注意到 JSON 输出没有 Content-type。您可以将此行添加到index.php 以使其工作。

    $app->contentType("application/json");
    

    您还可以获取successerror callacks 以查看它们是否已被调用。

    test.save(null, {
        success: function() {
            alert("success");
        },
        error: function() {
            alert("error");
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-23
      • 2015-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多