我有这个骨干代码,创建一个视图和模型,并调用save方法将数据保存到数据库:
var form = document.forms[0];
var RetailerModel = Backbone.Model.extend({
urlRoot: ' retailer.php',
defaults: {
name: 'company-name',
address: 'company-address',
phone: 'company-phone',
icon: 'http://localhost/icon.png'
}
});
var RetailerCollection = Backbone.Collection.extend({
});
var RetailerView = Backbone.View.extend({
className: 'retailer',
template: _.template($('#retailer-template').html()),
initialize: function() {
var obj = {
name: form.name.value,
address: form.address.value,
phone: form.phone.value
};
var o = this;
this.model.save(obj, {
success: function(model, response) {
console.log(model);
console.log(response);
o.render();
console.log('success');
},
error: function(model, response) {
console.log(model);
}
});
},
render: function() {
$('#retailer-list').append(this.$el.html(this.template(this.model.toJSON())));
return this;
}
});
var RetailerViews = Backbone.View.extend({
});
$('#submit').click(function(e){
var retailer_model = new RetailerModel();
var retailer_view = new RetailerView({model: retailer_model});
form.reset();
});
Run Code Online (Sandbox Code Playgroud)
用于接收数据的php代码如下:
<?php
$connect = mysql_connect('127.0.0.1','root','xxxxxx');
if (!$connect) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("retail", $connect);
if($_SERVER['REQUEST_METHOD'] == 'POST') //POST GET PUT DELETE
{
$data = json_decode(file_get_contents('php://input'), true);
}
$name = $data['name'];
$address = $data['address'];
$phone = $data['phone'];
$icon = $data['icon'];
if(!(mysql_query("INSERT INTO retailer (name, address, phone, icon)VALUES ('".$name."', '".$address."','$phone', '".$icon."')")))
{
echo 200;
}
else{
echo 'record has not been insert to db';
}
mysql_close($connect);
?>
Run Code Online (Sandbox Code Playgroud)
我遇到的一个问题是,当调用错误函数时,从服务器返回的模型仍然具有修改的属性.我想知道为什么会发生这种情况,我怎样才能确保如果发生错误,模型保持不变.
另一个问题是在php代码中,当sql查询成功时,如果我回显200或'200',主干会调用成功,但如果我回显一个字符串,主干会调用错误,我想知道背后的逻辑是什么它.
Cub*_*Eye 28
如果您想在模型上设置新属性之前等待服务器,请传递{wait:true}.
如果您不希望模型更新,直到保存成功完全传递wait: true为选项.
this.model.save(obj, {
success: function(model, response) {
console.log(model);
console.log(response);
o.render();
console.log('success');
},
error: function(model, response) {
console.log(model);
},
wait: true // Add this
});
Run Code Online (Sandbox Code Playgroud)
骨干
save( so are others like fetch, update...)
Run Code Online (Sandbox Code Playgroud)
返回一个承诺.您可以使用
save().done(
function( data ) {}, // success
function( err ) {} // fail
)
Run Code Online (Sandbox Code Playgroud)
就像你处理承诺一样.done()保证在服务器返回内容后执行该方法.
有关更多信息,请参阅AJAX.jqXHR的jQuery API文档.
| 归档时间: |
|
| 查看次数: |
26076 次 |
| 最近记录: |