Yii2 method to automatically obtain form data based on Ajax_php example

WBOY
Release: 2016-08-17 13:02:32
Original
1136 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 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 this 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 monitor the select through JS. When the select changes, use jQuery's get method to obtain 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 select

<?php
$script = <<registerJs($script);
?>

Copy after login

Readers who are interested in more Yii-related content can check out the special topics on this site: "Introduction to Yii Framework and Summary of Common Techniques", "Summary of Excellent PHP Development Framework", "Basic Tutorial for Getting Started with Smarty Templates", "Introduction to PHP Object-Oriented Programming" Tutorial", "php string usage summary", "php+mysql database operation introductory tutorial" and "php common database operation skills summary"

I hope this article will be helpful to everyone’s PHP program design based on the Yii framework.

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 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!