繁体   English   中英

骨干网:将数据传递到服务器(save()方法,php文件)

[英]Backbone: passing data to server (save() method, php file)

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

我想使用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时,一切都可以(在下面的代码中对此进行了注释)。 我可以创建模型,集合,视图等并对其进行操作。

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

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

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

您还可以获取successerror信息,以查看是否已被调用。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM