我想在下面的代码中实现类似的东西。只是代码正在从数据库发出请求,我想向数据库发送请求
$.post( "/trobay/categories/default/lists?parent_id="+$(this).val(), function( data ) {
如何发送请求添加属性名称和属性值以保存在DB中 下面是我的代码我已经
<?php
$script = <<< JS
$(document).ready(function(){
//setup before functions
var typingTimer;
var doneTypingInterval = 3000;
var \$TitleInput = $('#product-product_title');
//on keyup, start the countdown
\$TitleInput.on('keyup input change paste',function(){
clearTimeout(typingTimer);
if (\$TitleInput.val()) {
typingTimer = setTimeout(doneTyping, doneTypingInterval);
}
});
//user is "finished typing," do something
function doneTyping () {
data = \$TitleInput.val();
$.ajax({
url: '/trobay/draft/create',
type: 'POST',
data: data,
success: function (data) {
alert(data)
},
error: function(jqXHR, errMsg) {
// handle error
alert(errMsg);
}
});
}
});
JS;
$this->registerJs($script);
?>
在我的控制器中我有这个
public function actionCreate()
{
$model = new Draft();
if ($model->load(Yii::$app->request->post())) {
$model->created_at = \time();
if($model->save()){
return draftId;
}else{
return '0';
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
在我看来我有这个
<?php $form = ActiveForm::begin(['id'=>$model->formName(),
'enableClientValidation'=> true,
'fieldConfig' => ['template' => '{label}{input}{hint}']]); ?>
<div class="row">
<div class="col-md-12">
<?= $form->field($model, 'product_title')->textInput([
'class'=>'title-input',
'placeholder' => 'Give us a title for your items(include size,brand,color,material. e.t.c)',
])->label(false) ?>
</div>
<div class="col-md-12 text-muted">
E.g Men's blue addidas glide running shoes size 11
</div>
</div>
<?= $form->field($model, 'user_id')->textInput() ?>
<?= $form->field($model, 'product_title')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'product_name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'product_description')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'category_id')->textInput() ?>
现在我的问题是我只想获取每个字段输入的值并将其发送到服务器端以便在DB中保存而无需提交整个表单 关于JS代码的工作原理足以获取值,但我如何将其发送到服务器以进行保存
答案 0 :(得分:0)
//user is "finished typing," do something
function doneTyping () {
data = \$TitleInput.val();
$.ajax({
url: '/trobay/draft/create',
type: 'POST',
data: {title: data}
success: function (data) {
alert(data)
},
error: function(jqXHR, errMsg) {
// handle error
alert(errMsg);
}
});
});
如果您需要发送更多键值,请将其添加为逗号分隔值,如
data: {title: data, attr:"value"}
等等......您可以在控制器中将此值作为post参数接收。