如何在不提交表单的情况下获取表单外的输入控件值?

时间:2016-09-26 04:35:39

标签: javascript php

我花了近一个小时谷歌搜索它,但我发现没有任何帮助, 这是我的代码

<div class = "form-group col-md-12">
    <input type="text"  name="filename" id="filename"></input>
</div>

它在形式之外,我想做的是我在那里输入的内容应该放在这里

 $fopen=fopen( $uploadpath.here.'.png','wb');

所以我可以管理文件名,因此它不会是静态的。

2 个答案:

答案 0 :(得分:0)

您必须将数据发送到后端代码(php),因为它一旦运行到浏览器就不会运行。如果我是对的,您想要在后端打开文件,但您的页面可能会重新加载,因此您不想提交表单。如果是这种情况,您可以使用ajax,如下所示:

<div class = "form-group col-md-12">
    <input type ="text"  name = "filename" id="filename"></input>
</div>
<script>
var filename = $("#filename").val();
$.ajax({
    url: myfile.php, //url to your php file with code  $fopen=fopen( $uploadpath.here.'.png','wb');
    type: post,
    data: {"fileName":filename},
    success: function(result) {
        // use your code to handle the result whatever you want to do here
    }
})
</script>

你的php文件

myfile.php

<?php
$uploadPath = $_POST['fileName'];
$fopen=fopen( $uploadpath.here.'.png','wb');
echo "success"; // you can return whatever you want and that will go to success function in your javascript

?>

答案 1 :(得分:0)

使用jquery ajax $ .post它更容易

<div class = "form-group col-md-12">
    <input type ="text"  name = "filename" id="filename"></input>
</div>
<script>
var filename = $("#filename").val();
$.post("yourfile.php", {"fileName":filename}, function(data) {
    // do something
})
</script>

你的php

<?php
    $uploadPath = 'youruploadfolder'; // this is the location of your file folder
    $fileName = $_POST['fileName'];  // this is your file passed via ajax request
    $fopen = fopen($uploadpath.$fileName.'.png','wb');
    echo "success"; // you can return whatever you want and that will go to success function in your javascript
?>