2014-01-18 30 views
0

希望你能帮我解决这个问题。骨干:将数据传递给服务器(save()方法,php文件)

我想使用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是OK(它的评论在下面我的代码)。我可以创建模型,集合,视图等并对它们进行操作。

我试图使用这些教程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) 

回答

0

这里是一个工作示例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"); 
    } 
}); 
相关问题