打开一个新窗口,然后提交表格

时间:2018-11-02 11:11:40

标签: javascript html forms onsubmit

如何打开新窗口,然后使用HTML \ Javascript触发表单提交?

注意:target =“ _ blank”不是解决方案,因为它会将响应重定向到新窗口,而我需要从新窗口触发提交操作。

1 个答案:

答案 0 :(得分:1)

我会保留'_blank'来触发新的标签页/窗口,并使用jQuery和Ajax提交表单...

带有表单的标准html页面...

HTML

<form id="myForm">
    <input name="input1" type="text" value="somevalue1"/>
    <input name="input2" type="text" value="somevalue2"/>
    <a href="whereEverYouWantToGo.php" target="_blank" id="myFormButton">Send</a>
</form>

<input id="result1" value=""/> <?php //use if only wanting to get result back ?>

此页面使用的jQuery ...

jQuery

$(document).ready(function() {
    $(document).on("click","#myFormButton", function() {

        var str = $("#myForm").serialize(); // This grabs all your form inputs by name and creates a string e.g. input1=someValue1&input2=someValue2 which you can use later for grabbing the $_GET variables.

        $.ajax({
        cache: false,
        url: 'ajax/your-ajax-page-to-submit-the-form.php?'+str,            
        type: 'POST',
        dataType: 'json',
        success: function(result) {
            alert("success");

            // Can get data from Ajax file by using array cretaed in the file (see below)
            $('#result1').val(result['result1_from_ajax']);

        },
        error : function () {
            alert("error");
        }
    });
});

现在是Ajax页面...

您的ajax页面提交form.php

ob_start(); //at the very beginning start output buffereing

$var_input1 = mysqli_real_escape_string($dbc, $_GET['input1']);
$var_input2 = mysqli_real_escape_string($dbc, $_GET['input2']);

$q = "INSERT INTO my_table (column1, column2) VALUES ('$input1', '$input2')";
$dbc = mysqli_connect('localhost', 'root', 'password', 'DB_Name') OR die('Could not connect because: '.mysqli_connect_error()); 
$r = mysqli_query($dbc, $q);

// bof if you want to output any results or values back to jQuery
$var = array(
    'result1_from_ajax' => $var_input1,
    'result2_from_ajax' => $var_input2
);
// eof if you want to output any results or values back to jQuery

// Must have
ob_end_clean(); // right before outputting the JSON, clear the buffer.
echo json_encode($var);