gpt4 book ai didi

javascript - 打开新窗口并提交表单

转载 作者:行者123 更新时间:2023-12-03 00:49:27 26 4
gpt4 key购买 nike

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

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

最佳答案

我会保留“_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页面要提交的表单.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);

关于javascript - 打开新窗口并提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53117501/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com