Heim  >  Artikel  >  Backend-Entwicklung  >  Yii2基于Ajax自动获取表单数据的方法_php实例

Yii2基于Ajax自动获取表单数据的方法_php实例

WBOY
WBOYOriginal
2016-08-17 13:02:321264Durchsuche

本文实例讲述了Yii2基于Ajax自动获取表单数据的方法。分享给大家供大家参考,具体如下:

这里有两张表,表结构如下,locations表存放的省份和邮编等信息,两张表的model和curd均使用gii生成

yii2advanced.customers表

customer_id:int(11)
customer_name:varchar(100)
zip_code:varchar(20)
city:varchar(100)
province:varchar(100)

yii2advanced.locations表

location_id:int(11)
zip_code:varchar(20)
city:varchar(100)
province:varchar(100)

这里要通过在customer选择zip_code之后自动在表单中填充这个邮编对应的城市和省份信息

实现方法

首先需要在Locations控制器里面添加一个方法,他可以通过get过来的zip_id获取对应的location信息

public function actionGetCityProvince($zipId)
{
  $location = Locations::findOne($zipId);
  echo Json::encode($location);
}

然后通过JS监听select,当select改变时,使用jQuery的get方法获取对应的信息,并使用jQuery的attr方法设置city和province的value即可

JS代码,位于customer的form视图

#zipCode 是select的id

<&#63;php
$script = <<<JS
jQuery('#zipCode').change(function(){
  var zipId = $(this).val();
  jQuery.get('index.php&#63;r=locations/get-city-province',{zipId:zipId},function(data){
    var data = jQuery.parseJSON(data);
    jQuery("#customers-city").attr("value",data.city);
    jQuery("#customers-province").attr("value",data.province);
  });
 
});
JS;
$this->registerJs($script);
&#63;>

更多关于Yii相关内容感兴趣的读者可查看本站专题:《Yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn