我在我的模块COMPANY / Shippingagent上设置了一个模型 我的配置看起来像这个
<?xml version="1.0"?>
<config>
<modules>
...
</modules>
<admin>
<routers>
...
</routers>
</admin>
<global>
<models>
<Shippingagent>
<class>COMPANY_Shippingagent_Model</class>
<resourceModel>Shippingagent_Mysql4</resourceModel>
</Shippingagent>
<Shippingagent_mysql4>
<class>COMPANY_Shippingagent_Model_Mysql4</class>
<entities>
<Shippingagent>
<table>Shippingagent</table>
</Shippingagent>
</entities>
</Shippingagent_mysql4>
</models>
<resources>
<Shippingagent_setup>
<setup>
<module>COMPANY_Shippingagent</module>
</setup>
<connection>
<use>core_setup</use>
</connection>
</Shippingagent_setup>
<Shippingagent_write>
<connection>
<use>core_write</use>
</connection>
</Shippingagent_write>
<Shippingagent_read>
<connection>
<use>core_read</use>
</connection>
</Shippingagent_read>
</resources>
</global>
</config>
在我的布局上,我放置了
<?php echo Mage::app()->getLayout()->createBlock('core/template')
->setTemplate('company/shipping_template.phtml')->toHtml(); ?>
模板看起来像
<div class="input-box" align= right>
<input type="text" class="input-text required-entry" id="shipAgent" >
<input type="button" id="newship" value="Add New Agent" >
</div>
<script>
jQuery("#newship").click(function() {
//console.log('test');
var jsonObject = {};
jsonObject.brand = jQuery("#shipAgent").val();
jQuery.ajax({
url: '/shippingagent/Agent/setAgent',
dataType: 'json',
data:{
json: JSON.stringify(jsonObject),
},
success:function(data){
jQuery('#success').html("Success");
jQuery('#success').css('color', 'green');
}
});
});
</script>
我的控制器看起来像这样:
public function setAgentAction() {
$json = $this->getRequest()->getParam('json');
$json = json_decode($json);
foreach($json as $k => $v) {
if($k == 'brand')
$brand = $v;
}
//Send $json to the model
$data = array(
'title'=>$brand
);
$model = Mage::getModel('COMPANY_Shippingagent/Shippingagent')->setData($data);
try {
$insertId = $model->save()->getId();
echo "Data successfully inserted. Insert ID: ".$insertId;
} catch (Exception $e){
echo $e->getMessage();
}
}
}
我的模型看起来像这样:
class COMPANY_Shippingagent_Model_Mysql4_Shippingagent extends Mage_Core_Model_Mysql4_Abstract
{
public function _construct()
{
$this->_init('Shippingagent/Shippingagent', 'Shippingagent_id');
}
}
我的桌子看起来像这样:
<?php
$installer = $this;
$installer->startSetup();
$installer->run("
-- DROP TABLE IF EXISTS {$this->getTable('COMPANY_Shippingagent/Shippingagent')};
CREATE TABLE {$this->getTable('COMPANY_Shippingagent/Shippingagent')} (
`Shippingagent_id` int(11) unsigned NOT NULL auto_increment,
`title` varchar(255) NOT NULL default '',
PRIMARY KEY (`Shippingagent_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
");
$installer->endSetup();
我在使用json传递值时出错,并且永远不会创建表。 我不知道我做错了什么,但我怀疑问题出现在我的控制器之后的$ data声明,因为当我评论所有那个部分和echo $ brand它实际上显示了我想要添加到表中的值。 有任何想法吗?我在这里疯了......