简体   繁体   English

如何将值传递给JS函数,然后传递给PHP脚本

[英]How to pass value to JS function and, then, to PHP script

I want to show the result of PHP script on div tag without page refresh. 我想在没有页面刷新的情况下在div标签上显示PHP脚本的结果。 I have a list of .c files (the users can compile them on server)... 我有一个.c文件列表(用户可以在服务器上编译它们)...

<option value="" selected="selected">Choose file </option>';

                    $dirPath = dir('directoryExample');
                    while (($file = $dirPath->read()) !== false)
                        {
                            if ($file == '.' || $file == '..') continue;
                            echo "<option value=\"" . trim($file) . "\">" . $file . "\n";
                        }
                    $dirPath->close();
                    echo '</select>

...and two div and button like this: ...以及两个div和按钮,如下所示:

<div id="2" style="display:none;">  </div>
<div id="1" style="display:visible;"> Compile...</div>
<button type="button" onclick="codiad.ccomp.compile(this.value);">Compile</button>

First question: How can I pass selected file to JQuery function? 第一个问题:如何将所选文件传递给JQuery函数? this.value works fine? this.value工作正常吗?

This is the Jquery function: 这是Jquery函数:

compile: function(value) {

            if(($('#1').css('display')!='none')){
                    $('#2').load(this.path+'\compile.php').show().siblings('div').hide();
            }else if($('#2').css('display')!='none'){
                    $('#1').show().siblings('div').hide();
                }

    }

The code works fine but this is second question: how can I pass now the value to php page? 代码工作正常,但这是第二个问题:我现在如何将值传递给php页面?

Thanks in advance! 提前致谢!

You can pass a data argument to .load() . 您可以将数据参数传递给.load()

$('#2').load(this.path+'/compile.php', { file: $("#selectID").val() })
    .show().siblings('div').hide();

In the PHP script, use $_GET['file'] to get the selected filename. 在PHP脚本中,使用$_GET['file']获取选定的文件名。

I don't think that in your first question this.value will work fine as this refers to the button, not the select element. 我认为在您的第一个问题中, this.value可以正常工作,因为this是指按钮而不是select元素。

Instead you would need something like: 相反,您将需要以下内容:

$('#your_select_element').val();

And you can remove the inline javascript and use something like: 您可以删除内联JavaScript并使用类似以下内容的代码:

$('button').on('click', function() {
  // do something with `$('#your_select_element').val();`
  ...
}

Assuming there is one button, you might need to add a class or ID to address it specifically. 假设有一个按钮,您可能需要添加一个类或ID来专门解决它。

And as mentioned in the other answer, you can add a data parameter to your .load() function. 如另一个答案中所述,您可以将数据参数添加到您的.load()函数中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM