Home > php教程 > PHP开发 > body text

Yii2 method to automatically obtain form data based on Ajax

高洛峰
Release: 2016-12-23 16:48:11
Original
1664 people have browsed it

The example in this article describes how Yii2 automatically obtains form data based on Ajax. Share it with everyone for your reference. The details are as follows:

There are two tables here. The table structure is as follows. The locations table stores information such as provinces and postal codes. The model and curd of the two tables are both generated using GII.

yii2advanced.customers table

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

yii2advanced.locations table

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

Here we need to automatically fill in the city and province information corresponding to the zip code in the form after the customer selects zip_code

Implementation method

First You need to add a method in the Locations controller. He can get the corresponding location information by getting the zip_id

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

Then listen to the select through JS. When the select changes, use jQuery's get method to get the corresponding information. And use jQuery's attr method to set the value of city and province

JS code, located in the customer's form view

#zipCode is the id of the select

<?php
$script = <<<JS
jQuery(&#39;#zipCode&#39;).change(function(){
  var zipId = $(this).val();
  jQuery.get(&#39;index.php?r=locations/get-city-province&#39;,{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);
?>
Copy after login

I hope this article will help everyone use PHP based on the Yii framework Programming helps.

For more articles related to Yii2’s method of automatically obtaining form data based on Ajax, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!