簡體   English   中英

如何從ajax從下拉列表中獲取價值並將其發送給php?

[英]how to take value from drop down list by ajax and send it to php?

我有一些類別名稱的下拉列表,我想使用ajax來獲取所選類別的名稱,並將它們發送到ajax腳本位於其中的同一php頁面,這是我的新代碼

創建動作代碼:

public function actionCreate()
    {
        $model=new News;

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

                if(isset($_POST['category']))
                       $category = $_POST['category'];
                   else
                       $category = NULL;

        if(isset($_POST['News']))
        {
            $model->attributes=$_POST['News'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->id));
        }

        $this->render('create',array(
            'model'=>$model, 'category'=>$category
        ));
    }

表格代碼:

<div class="row">
        <?php echo CHtml::label('Choose category to add from',''); ?>
                <?php $data = array('celebrities'=>'Celebrities', 'events'=>'Events', 'videos'=>'Videos', 'editorials'=>'Editorials'); ?>
        <?php echo CHtml::dropDownList('category', '', $data); ?>
    </div>
        <script type="text/javascript">

            $("#category").change(function(){
                var category = $(this).val();

            $.ajax({
                url:'/tonyward/index.php/news/create',
                data:{category:category},
                type:'POST',
                dataType:'html',
                success:function(data) {
                    console.log(data.category)
                },
                cache:false
            });
        });
        </script>

        <div class="row">
        <?php echo $form->labelEx($model,'idItem'); ?>
                <?php $data = array('celebrities'=>$category); ?>
        <?php echo CHtml::dropDownList('subcategory', '', $data); ?>
                <?php echo $form->error($model,'idItem'); ?>
    </div>

現在第二個下拉列表的數據將如何更改?

舊代碼:

<div class="row">
            <?php echo CHtml::label('Choose category to add from',''); ?>
                    <?php $data = array('celebrities'=>'Celebrities', 'events'=>'Events', 'videos'=>'Videos', 'editorials'=>'Editorials'); ?>
            <?php echo CHtml::dropDownList('category', '', $data); ?>
        </div>

    <script type="text/javascript">

        $("#category").change(function(){

            $("#category").change(function(){

                var category = $(this).val();

                $.ajax({
                    url:window.location.href,
                    type:'GET',
                    data:{category:category},
                    dataType:'json',
                    cache:false,
                    success:function(data){

                    },
                });
            });
    </script>

    <?php 
        if(isset($_GET['category'])){

            $category = $_GET['category'];

            echo "<script>alert('done');</script>";
        }
    ?>

select標記沒有href因此this.href不會為您的AJAX生成有效的URL。

您是否知道您的頁面AJAX調用會返回整個頁面以及<script>alert('done');</script> 確實不是 dataType選項指定的json 因此,我希望會有一個parse error並且沒有要觸發的.error處理程序。 如果呼叫success 完成,則不呈現返回的內容 ...因此,您將不會看到警報。

意見建議

  1. 更改您的PHP腳本,以便在設置category時僅返回if塊內的代碼
  2. 代替<script>alert('done');</script>只需使用done ==>`echo“ done”
  3. success處理程序中,包括alert( data )
  4. dataType更改為text
  5. 包括一個error處理程序,以防萬一。
  6. 當基於客戶端代碼提出問題時,通常包含相關部分的HTML(由瀏覽器呈現)而不是服務器端代碼會很有幫助。 我無法確定PHP代碼中的category是: idname ...,而其他許多category可能存在相同的問題,因此可以避免該問題。

我如何解決我的問題?

  1. 我創建了一個名為selectedCategory()的函數。
  2. selectedCategory()renderPartial下拉列表的html代碼,它們寫在_categoryItems.php中。
  3. 我在第一個下拉類別('#category')的更改上調用了ajax函數。
  4. Ajax函數將發布到selectedCategory() ,最后它將在特定div中成功加載html數據。

這是代碼:

形式和ajax功能代碼:

<div class="row">
        <?php echo CHtml::label('Choose category to add from',''); ?>
                <?php $data = array('Celebrities'=>'Celebrities', 'Events'=>'Events', 'Videos'=>'Videos', 'Editorials'=>'Editorials'); ?>
        <?php echo CHtml::dropDownList('category', '', $data, array(
                    'empty'=>'select category'
                )); ?>
    </div>
        <script type="text/javascript">

            $(function() {

                document.getElementById('itemslabel').style.display='none';
            });

            $("#category").change(function(){

                document.getElementById('itemslabel').style.display='block';
                var category = $(this).val();

                if(category === ''){

                    document.getElementById('items').style.display='none';
                }

                else{

                    $.ajax({
                        url:'/tonyward/index.php/news/selectedCategory',
                        data:{category:category},
                        async:true,
                        type:'POST',
                        dataType:'html',
                        success:function(data) {

                            document.getElementById('items').style.display='block';
                            $('#categoryItems').html(data);
                        },
                        cache:false
                    });
                }
        });
        </script>

        <div class="row" id="items">
        <?php echo $form->labelEx($model,'idItem', array('id'=>'itemslabel')); ?>
                <div id="categoryItems"></div>
                <?php echo $form->error($model,'idItem'); ?>
    </div>

selectedCategory動作selectedCategory代碼:

public function actionSelectedCategory(){

            if(Yii::app()->request->isAjaxRequest){

                $category = $_POST['category'];

                $this->renderPartial('_categoryItems', array(
                   'category'=>$category 
                ));
            }
        }

_categoryItems代碼:

<?php $data = CHtml::listData($category::model()->findAll(), 'id', 'thumbtitle'); ?>
<?php echo CHtml::dropDownList('subcategory', '', $data); ?>

注意:我通過我的js代碼顯示和隱藏了一些元素。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM