javascript Yii2:用按钮调用javascript函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28901294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 09:44:19  来源:igfitidea点击:

Yii2: call javascript function with a button

javascriptphpjqueryhtmlyii2

提问by LuisRox

I want to call a javascript function from a button in php

我想从 php 中的按钮调用一个 javascript 函数

this is the php code:

这是php代码:

//the view
    <?php

    $form = yii\widgets\ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); 

    ?>

 <?=

$form->field($msubs, 'id_subespecifica', ['options' => ['class' => 'col-md-12']])
  ->widget(Select2::classname(),[
        'data' => ArrayHelper::map($vectorConsul,'sesp', 'sesp'),
        'options' => ['id' => 'prueba'],
        ])

  ->label(false);


 ?>


    <button class="btn btn-primary" onclick="myFunction()">Add New</button>


<?php
yii\widgets\ActiveForm::end(); 
?>

And this is the Javascript code:

这是 Javascript 代码:

//Javascript
function myFunction() {
$.ajax({
  url:'partidaasociada/get-linea',
  type:'POST',
  dataType:'json',
  data:{pruebaId:$('#prueba').val()}
  // alert(pruebaId);
});

In the javascript function, i need to send the $('#prueba').val() to a php function in the controller:

在 javascript 函数中,我需要将 $('#prueba').val() 发送到控制器中的 php 函数:

//Controller
public function actionGetLinea($pruebaId)
{
    $model = new PartidaAsociada();
    log($pruebaId);
}

But i am getting some errors, i think the button is reloading the whole form and don't recognize the previous data y sent to the form.

但是我遇到了一些错误,我认为按钮正在重新加载整个表单并且无法识别发送到表单的先前数据。

Note: The 'alert()' in the javascript function is on commentary because it wont let me use, the form stay loading when i put the alert. thanks beforehand.

注意:javascript 函数中的“alert()”在注释中,因为它不会让我使用,当我放置警报时表单会保持加载状态。预先感谢。

回答by mkaatman

I think part of the problem is you aren't preventing the default action of a button click.

我认为问题的一部分是您没有阻止按钮单击的默认操作。

We can clean things up a bit too. Hit control+shift+i and choose the console tab to see console.log output.

我们也可以稍微清理一下。按 control+shift+i 并选择控制台选项卡以查看 console.log 输出。

HTML:

HTML:

<button class="btn btn-primary _addNew">Add New</button>

<button class="btn btn-primary _addNew">Add New</button>

Javascript:

Javascript:

$('._addNew').on('click', function(event){
    event.preventDefault();
    var data = {};
    data.pruebaId = $('#prueba').val();

    var success = function(data){
       console.log("Success!", data);
    }
    var error = function(data){
       console.log("Error!", data);
    }
    $.ajax({
      url:'partidaasociada/get-linea',
      type:'POST',
      dataType:'json',
      data:data
   }, success, error);
});